2017-02-10 47 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 
} 

希望它能幫助!