Created
November 8, 2023 05:49
-
-
Save tgnivekucn/b331dd260eb87ff296303994525f6314 to your computer and use it in GitHub Desktop.
Opaque types v.s. Boxed types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol Shape { | |
associatedtype T | |
func draw() -> String | |
} | |
struct Triangle: Shape { | |
typealias T = Int | |
var size: Int | |
func draw() -> String { | |
var result: [String] = [] | |
for length in 1...size { | |
result.append(String(repeating: "*", count: length)) | |
} | |
return result.joined(separator: "\n") | |
} | |
} | |
struct Square: Shape { | |
typealias T = Int | |
var size: Int | |
func draw() -> String { | |
let line = String(repeating: "*", count: size) | |
let result = Array<String>(repeating: line, count: size) | |
return result.joined(separator: "\n") | |
} | |
} | |
// Opaque types | |
// Compile error: Conflicting arguments to generic parameter 'τ_0_0' ('Square' vs. 'Triangle') | |
var tmp1: [some Shape] = [Square(size: 1), Triangle(size: 1)] //[Square(size: 1), Square(size: 2)] | |
// Boxed types | |
var tmp2: [any Shape] = [Square(size: 1), Triangle(size: 1)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment