如何扩展满足多个约束的协议 - Swift 2.0

Aud*_* Li 27 protocols swift2

我正在尝试扩展协议,以便它可以满足其他协议的多个约束.如何调整代码以使其正确?非常感谢.

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)

  • 当它必须符合两者时,这是很好的,但是如果你想要检查一个或另一个的一致性呢?类似于:扩展可移动的地方Self:protocol <Animal || 年龄> ... (2认同)

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)