示例工程 10-protocols
10-protocols/Sources/Ch10Kit/DefaultDispatch.swift
/// 默认实现的派发:协议要求会动态派发,扩展里「新增」的方法静态派发。
public protocol Greeter {
func greet() -> String
}
extension Greeter {
public func greet() -> String {
"default"
}
}
public struct PlainPerson: Greeter {
public init() {}
}
public struct CustomPerson: Greeter {
public init() {}
public func greet() -> String {
"custom"
}
}
/// 只有扩展方法、没有协议要求:这是最容易踩的坑。
public protocol Worker {}
extension Worker {
public func work() -> String {
"extension"
}
}
public struct ConcreteWorker: Worker {
public init() {}
public func work() -> String {
"concrete"
}
}
public enum DispatchLab {
/// 通过协议类型调用:走协议见证表,取到具体类型的实现。
public static func greetThroughProtocol(_ greeter: any Greeter) -> String {
greeter.greet()
}
/// 通过泛型调用:同样取到具体实现,且可被特化。
public static func greetThroughGeneric<T: Greeter>(_ greeter: T) -> String {
greeter.greet()
}
/// 具体类型直接调用。
public static func workConcrete() -> String {
ConcreteWorker().work()
}
/// 协议类型调用:`work` 不在协议要求里,只能静态派发到扩展实现。
public static func workThroughProtocol() -> String {
let worker: any Worker = ConcreteWorker()
return worker.work()
}
}