我正在尝试扩展协议,以便它可以满足其他协议的多个约束.如何调整代码以使其正确?非常感谢.
extension Moveable where Self: Animal && Self: Aged {
public var canMove: Bool { return true }
}
Run Code Online (Sandbox Code Playgroud)

ABa*_*ith 60
您可以使用协议组合:
extension Moveable where Self: protocol<Animal, Aged> {
// ...
}
Run Code Online (Sandbox Code Playgroud)
或者只是一个接一个地添加一致性:
extension Moveable where Self: Animal, Self: Aged {
// ...
}
Run Code Online (Sandbox Code Playgroud)
kga*_*dis 33
截至本文发表时,答案正在使用中protocol<Animal, Aged>.
在Swift 3.0中,protocol<Animal, Aged>不推荐使用.
Swift 3.0中的正确用法是:
extension Moveable where Self: Animal & Aged {
// ...
}
Run Code Online (Sandbox Code Playgroud)
您还可以将协议与a组合使用typealias.当您在多个位置使用协议组合时,这非常有用(避免重复并提高可维护性).
typealias AgedAnimal = Aged & Animal
extension Moveable where Self: AgedAnimal {
// ...
}
Run Code Online (Sandbox Code Playgroud)