Swift Academy · 课时

any P(存在类型):权衡与动态分派

使用 any P ,将不同类型的符合者存储或传递在协议之后。了解动态分派、装箱,以及 关联类型 / Self 要求带来的限制。

第 2 / 3 课8 个步骤

any P(存在类型):权衡与动态分派 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 2 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 3 节课。

什么是存在类型?

存在类型(any P)可以容纳符合 P 的任意值。它们支持异构存储和动态分派,但存在一些限制。

  • 非常适合混合集合
  • 通过协议见证表进行动态分派
  • 对关联类型/Self 存在限制

异构集合

any Shape 允许您将不同的符合类型存储在一起,并通过动态分派调用协议方法。

protocol Shape { func area() -> Double }

struct Circle: Shape { let r: Double; func area() -> Double { .pi * r * r } }
struct Square: Shape { let s: Double; func area() -> Double { s * s } }

// Heterogeneous array using ANY Shape
let shapes: [any Shape] = [Circle(r: 1), Square(s: 2), Circle(r: 0.5)]
let total = shapes.reduce(0) { $0 + $1.area() }   // dynamic dispatch
print(String(format: "%.2f", total))

接口边界

存在类型只公开协议接口。仅具体类型才有的方法需要进行向下转型(这是可选的,并且会在运行时检查)。

extension Circle { func diameter() -> Double { 2 * r } }

let mixed: [any Shape] = [Circle(r: 1), Square(s: 3)]
print(mixed[0].area())            // OK: in protocol
// print(mixed[0].diameter())     // ❌ Not visible via any Shape (commented)
// You'd need a type check / downcast:
if let c = mixed[0] as? Circle { print(c.diameter()) }

关联类型注意事项

存在类型无法直接携带未知的关联类型或涉及 Self 的要求。请使用类型擦除,或通过包装器固定关联类型。

// Protocols with associated types/Self constraints can be hard to use as existentials.
protocol Parser {
    associatedtype Output
    func parse(_ s: String) -> Output
}

// let p: any Parser = ...     // ❌ Not directly usable: Output is unknown
// Workarounds: type erasure or constrain Output to a specific type in wrappers.

选择参数形式

存在类型:异构且灵活。泛型:同质,并且更快或可在编译时检查。请根据需求选择。

// Existential: accepts any mix of Shapes (dynamic dispatch)
func totalAreaExistential(_ xs: [any Shape]) -> Double {
    xs.reduce(0) { $0 + $1.area() }
}

// Generic (homogeneous): static dispatch; one concrete Shape type per call
func totalAreaGeneric<S: Sequence, T: Shape>(_ xs: S) -> Double
where S.Element == T {
    xs.reduce(0) { $0 + $1.area() }
}

print(totalAreaExistential([Circle(r:1), Square(s:2)]))  // mixed OK
print(totalAreaGeneric([Circle(r:1), Circle(r:2)]))      // homogeneous only
// totalAreaGeneric([Circle(r:1), Square(s:2)])          // ❌ different types

何时使用 any P

指南:

  • 使用 any P 进行异构存储和运行时多态。
  • 当元素同质时,若注重性能和静态保证,优先使用泛型。
  • 对于带有关联类型/Self 的协议,除非进行类型擦除或包装,否则应避免使用存在类型。

存在类型的优势

快速检查:any P 支持什么?

回顾

回顾:any P 是用于存放符合协议的值的存在类型容器。它通过动态分派支持异构多态,但会隐藏仅属于具体类型的接口,并且难以处理关联类型/Self。

免费开始

用 AI 导师学习 Swift — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
122
课程
409

常见问题解答

「any P(存在类型):权衡与动态分派」课时是免费的吗?

是的 — 「any P(存在类型):权衡与动态分派」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Swift Academy 课程的其余内容,请升级到 CoddyKit PRO。 Swift Academy 课程共包含 3 节课。

「any P(存在类型):权衡与动态分派」这节课中我会学到什么?

使用 any P ,将不同类型的符合者存储或传递在协议之后。了解动态分派、装箱,以及 关联类型 / Self 要求带来的限制。 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Swift Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Swift Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 3 节。

「any P(存在类型):权衡与动态分派」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Swift Academy 课中编写并运行代码吗?

能。每节 Swift Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. some P(不透明结果类型):隐藏具体类型
  2. any P(存在类型):权衡与动态分派
  3. 在 some、any 与泛型之间进行选择
← 返回 Swift Academy