╱🚧 under construction -> homogeneous type, heterogeneous type
Last updated 3 months ago
Was this helpful?
Swift ⟩ type ⟩ category ⟩ some╱any╱generics
some, any, generics 是三種特性不同的型別,比較如下:
some
any
範例
型別決定者
型別決定期
編譯期
執行期
允許多型別
否,單型別 (homogeneous type)
對使用者隱藏具體型別,故稱為 。
是,多型別
(heterogeneous type)
將具體型別封裝起來的型別,故稱為 。
介於是與否之間
使用者可指定不同的 T,因此可產生許多不同的具體型別。
T
不過一旦指定了 T ,此馬上變為單型別的具體型別。
roles:不同角色(實現者、使用者)對型別的不同控制權
// 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 }
let shape = makeCircle() // ⭐️ 使用者:只知道返回值是 `some MyShape` print(shape.area()) // ⭐️ 使用者:可使用 `MyShape` 的方法 let a = Container(value: 42) // ⭐️ 泛型的具體型別:`Container<Int>` // ⭐️ 決定者:使用者 // ⭐️ 決定期:編譯期 (compile time)
// 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)
// 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") } }
// 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)
Swift ⟩
Opaque and Boxed Protocol Types ⟩
Boxed Protocol Type (any)
Types ⟩
Opaque Types (some)
Boxed Protocol Types (any)
some (opaque type)
existential type
homogeneous type
heterogeneous type
ChatGPT ⟩ 學習 Swift ⭐️
Bakshi ⟩ some and any keyword in Swift ⭐️
SwiftSenpai ⟩ Understanding the “some” and “any” keywords in Swift 5.7
Swift 5.7 中的 any 和 some
type erasure
roles:不同(程式碼)角色對型別有不同的控制權。
// implementer func f() -> some Shape { Circle() } // user let a = f()
// implementer func g() -> any Shape { // omitted ... } // user let b = g()
// implementer struct Container<T> { var value: T } // user let c = Container(value: 42)