摘要
Protocol
是 Swift 中實現面向協議編程思想的重要部分。在使用過程中有遇到協議中聲明的部分,但是在遵守部分不需要實現的,那麼就需要使用extension
參與進來,讓Protocol
使用的更加靈活,得心應手。
Protocol
是 Swfit 中重要的編程方式,也就是面向協議編程。主要就是爲了解決繼承過程中造成的多態情況。除此之外,在項目中也常用到代理中。
這裏以遵守代理爲例,來看一下 Protocol
在使用過程中可能遇到的問題,首先可以創建一個 Protocol
結構。
protocol CustomProtocol {
}
在 CustomProtocol
結構中可以聲明屬性或者函數。這裏聲明一個 name
屬性和 running
函數。
protocol CustomProtocol {
var name: String { get set }
func running()
}
創建一個 Person
的 struct
類型數據,遵守 CustomProtocol
協議。
struct Person: CustomProtocol {
}
這時會報一個編譯錯誤,大致意思就是 Person
結構體沒有實現 CustomProtocol
協議中的屬性或者方法。
一般遇到這樣的錯誤,直接點擊 Fix
,Xcode 會幫你自動在 Person
中創建,然後你自己去設置一下就可以消除這個編譯錯誤。
struct Person: CustomProtocol {
var name: String {
get { "no name"}
set { }
}
func running() {
print("running until stop")
}
}
到這一步,就完成了 protocol
的使用操作,但是,如果我還有一個 Person2
的結構體類型也遵守協議,它只有 name
屬性,沒有 running
函數時,就依然報一個編譯錯誤:
這就太強迫人了,我就想做到想用就用,不想用就不用 running
函數,怎麼做?
Swift 給出的方案就是在 protocol
的 extension
中實現它。
extension CustomProtocol {
func running() {
print("running at CustomProtocol")
}
}
剛剛報的編譯錯誤就消除了。這時,你就可以在 Person2
中想用就用,不想用就不用。
總結
在 protocol
中聲明的屬性或者函數,當有 struct
或者 class
遵守時,就必須全部實現 protocol
中的屬性或者函數。
若要遵守 protocol
的 struct
或者 class
自己決定屬性或者函數實現與否,就要在 protocol
的 extension
中去先實現這些屬性或者函數。之後再在 struct
或者 class
中實現就相當於重寫的效果。
題外話
時間倉促,說的東西可能不全面,在你查看的過程中遇到什麼問題,評論區給我留言,我會盡快回復