๐ ็ฏไพไธ ๐ ็ฏไพไบ ๐ ๆๅ ๐ฅ ็ธ้ ๐ ๅ่
๐ roles ๏ผไธๅ่ง่ฒ(ๅฏฆ็พ่
ใไฝฟ็จ่
)ๅฐๅๅฅ็ไธๅๆงๅถๆฌ
๐ท ๅฏฆ็พ่
(implementer)
Copy // custom protocol
protocol MyShape {
func area () -> Double
}
// custom types conforming to MyShape
struct MyCircle : MyShape {
var radius: Double
func area () -> Double { . pi * radius * radius }
}
struct MySquare : MyShape {
var size: Double
func area () -> Double { size * size }
}
// return type: opaque type (some)
func makeCircle () -> some MyShape { // โญ๏ธ ่ฟๅๅผๅ
ท้ซๅๅฅ๏ผ`MyCircle`
return MyCircle ( radius : 10 ) // โญ๏ธ ๆฑบๅฎ่
๏ผๅฏฆ็พ่
} // โญ๏ธ ๆฑบๅฎๆ๏ผ็ทจ่ญฏๆ (compile time)
// return type: boxed protocol type (any)
func makeAnyShape () -> any MyShape { // โญ๏ธ ่ฟๅๅผๅ
ท้ซๅๅฅ๏ผ(ๅๆ
ๆฑบๅฎ)
let n = Int . random ( in : 1 ... 6 ) // โญ๏ธ ๆฑบๅฎ่
๏ผไฝฟ็จ่
return ( n % 2 == 0 ) // โญ๏ธ ๆฑบๅฎๆ๏ผๅท่กๆ (run time)
? MyCircle ( radius : 10 )
: MySquare ( size : 4 )
}
// generic type
struct Container < T > {
var value: T
}
๐งโ๐ผ ไฝฟ็จ่
(user)
Copy let shape = makeCircle () // โญ๏ธ ไฝฟ็จ่
๏ผๅช็ฅ้่ฟๅๅผๆฏ `some MyShape`
print ( shape.area ()) // โญ๏ธ ไฝฟ็จ่
๏ผๅฏไฝฟ็จ `MyShape` ็ๆนๆณ
let a = Container ( value : 42 ) // โญ๏ธ ๆณๅ็ๅ
ท้ซๅๅฅ๏ผ`Container<Int>`
// โญ๏ธ ๆฑบๅฎ่
๏ผไฝฟ็จ่
// โญ๏ธ ๆฑบๅฎๆ๏ผ็ทจ่ญฏๆ (compile time)
Copy // type of property
// -------------------------------
var a: View = Text ( "Hello" ) // โ๏ผ`View` has associatedtype 'Body`
var b: some View = Text ( "Hello" ) // โ
opaque type
var c: any View = Text ( "Hello" ) // โ
existential type
๐ associated type
๐ some (opaque type)
Copy // return type (of computed property)
// -------------------------------------
let n = Int . random ( in : 1 ... 5 )
// โ
OK (same type, homogeneous)
var a: some View {
if n % 2 == 0 { Text ( "Even" ) }
else { Text ( "Odd" ) }
}
// โ NG! (Text โ Label)
var b: some View {
if n % 2 == 0 { Text ( "Even" ) }
else { Label ( "Hello" , systemImage : "bolt.fill" ) }
}
// โ
OK (heterogeneous, implicit type erasure)
var c: any View {
if n % 2 == 0 { Text ( "Even" ) }
else { Label ( "Hello" , systemImage : "bolt.fill" ) }
}
๐ type erasure
Copy // homogeneous vs heterogeneous collection
var a: [ some Shape] = [ Circle () , Circle () ] // โ
OK (homogeneous)
var a: [ some Shape] = [ Circle () , Capsule () ] // โ NG! (Circle โ Capsule)
var a: [ any Shape] = [ Circle () , Capsule () ] // โ
OK (heterogeneous)
๐ฐ roles ๏ผไธๅ(็จๅผ็ขผ)่ง่ฒๅฐๅๅฅๆไธๅ็ๆงๅถๆฌใ