为什么要扩展自己的协议?

时间:2017-02-10 12:43:27

标签: swift protocols

我正在阅读Swift 3教程和文档,我发现在使用协议时,每个人都在使用一种设计模式。它首先声明一个包含少量变量的协议(有时只有一个或两个),然后创建一个对该协议的扩展,并在扩展中定义一些方法。例如(这实际上是一个愚蠢的代码示例,仅用于演示):

protocol Bicycle {
    var numberOfWheels: Int {get}
    var isMoving: Bool {get set}
}

extension Bicycle {
    func startPedaling() { isMoving = true }
    func stopPedaing() { isMoving = false }
}

协议和扩展由我完全控制(因为我是开发人员,我可以访问此资源文件)。此外,它们都位于同一资源文件中。

那么,为什么方法驻留在扩展中而不是原始协议中呢?例如:

protocol Bicycle {
    var numberOfWheels: Int {get}
    var isMoving: Bool {get set}

    func startPedaling() { isMoving = true }
    func stopPedaing() { isMoving = false }
}

谢谢, 鲍里斯。

1 个答案:

答案 0 :(得分:2)

也许在您提供的案例中,它可能没有多大意义,但在某些情况下,对您自己的协议的协议扩展非常强大,尤其是当您使用类获取扩展的约束时。

想象一下这个例子。如果bicicle是山地自行车,我会添加添加类似指南针"(不是最佳示例)的内容。然后我会做以下事情:

protocol Bicycle {
    var numberOfWheels: Int {get}
    var isMoving: Bool {get set}

extension Bicycle {
    func startPedaling() { isMoving = true }
    func stopPedaing() { isMoving = false }
}

extension Bicycle where Self: MountainBike {
    var compass: Compass {get}
}

class MountainBike: Bicycle {
    //Here you can use the compass
}

class NormalBike: Bicycle {
    //Here you can't use the compass
}
你知道吗?您可以为每个类添加特定的内容,因此可以对某些类进行某种程度的调整。现在,从MountainBike继承的每个类都可以使用指南针。

在这种情况下,它可能是简单的方式,而且好处不是那个条款,但有些情况下它可能非常有用,例如

protocol Controller {
    //some useful variables
}

extension Controller where Self: UIViewController {
    // Here you can use all the properties of a UIViewController
    // like getting the navigation controller, etc. Every
    // UIViewController subclass (or a UIViewController itself)
    // that conforms to it would get this methods
}

希望它有所帮助!