2017-02-10 52 views
1

我正在通过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

你的第二个例子不会编译。 - 在https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html中查找“提供默认实现”。 –

回答

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 
} 

希望它能帮助!