🔸user
// ⭐️ implementer: 
// 在這裡,`makeCircle` 就是實現者,他決定了返回值的具體型別是 `Circle`,
// 雖然對外只暴露 `some Shape`(使用者只知道返回值是 `some Shape`)。
func makeCircle(radius: Double) -> some Shape {
    return Circle(radius: radius)
}
// ⭐️ user:
// 呼叫 `makeCircle` 的程式碼就是使用者,使用者只知道返回型別符合 Shape 協議,
// 但不知道具體型別是什麼(因為返回值是 some Shape)。
let shape = makeCircle(radius: 5)// ⭐️ implementer: 定義型別、函數
// ------------------------------
protocol MyShape {
    func area() -> Double
}
struct MyCircle: MyShape {
    var radius: Double
    func area() -> Double { .pi * radius * radius }
}
func makeCircle() -> some MyShape {
    return MyCircle(radius: 10)      // ⭐️ 實現者決定具體型別:`MyCircle`
}
// ⭐️ user: 使用型別、函數
// ------------------------------
let shape = makeCircle()             // ⭐️ 使用者只能知道它是:`some MyShape`
print(shape.area())                  // ⭐️ 可使用 `MyShape` 協議的方法- ⚖️ some╱any╱generics:實現者與使用者對型別有不同的控制權。 
- ChatGPT ⟩ 學習 Swift 
Last updated
Was this helpful?