🔰roles

devterms ⟩ roles

角色
行為

實現者╱implementer

函數型別定義的人 (或程式碼)。

使用者╱user

使用函數型別定義的人 (或程式碼)。

終端使用者╱end user

使用應用程式的人 (不涉及程式開發)。

範例

// 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)

型別決定者

👷 實現者

🧑‍💼 使用者

🧑‍💼 使用者

型別決定期

⚙️ 編譯期

🏎️ 執行期

⚙️ 編譯期

允許多型別

單型別 (homogeneous type)

對使用者隱藏具體型別,故稱為 opaque type

,多型別

(heterogeneous type)

將具體型別封裝起來的型別,故稱為 boxed protocol type

介於是與否之間

使用者可指定不同的 T,因此產生許多不同的具體型別

不過一旦指定了 T 之後,此泛型馬上變為單型別的具體型別

👷 實現者 (implementer)
// 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)
let shape = makeCircle()        // ⭐️ 使用者:只知道返回值是 `some MyShape`
print(shape.area())             // ⭐️ 使用者:可使用 `MyShape` 的方法

let a = Container(value: 42)    // ⭐️ 泛型的具體型別:`Container<Int>`
                                // ⭐️ 決定者:使用者
                                // ⭐️ 決定期:編譯期 (compile time)

Last updated

Was this helpful?