Android編程中接口和抽象類的使用實際上是很是頻繁的,剛開始接觸Swift的時候,發現Swift裏面沒有抽象類這個概念,很是彆扭,其實Protocol就是相似Java中的接口和抽象類的東西。接下來咱們看看如何在Swift中實現一個抽象類。
學過Java的都知道,抽象類具備如下特性:程序員
Protocol最經常使用的方法是相似Java中的Interface,用來聲明一些子類必須實現的屬性和方法。
因此抽象方法就不須要咱們去思考了,很是簡單,直接在Protocol中聲明便可編程
protocol AbstractClass { var value : String{get set} func abstractFun() }
這個任務看上去很是簡單,隨便百度一下就知道,如何給Protocol擴展方法。swift
extension AbstractProtocol{ func extensionFun() { print("this is a extensionFun") } }
確實很是簡單,不過抽象類中的實體方法是能夠修改抽象方法中的參數的,可是上述代碼中,若是直接給抽象類中的屬性賦值,編譯器會報錯Cannot assign to property: 'self' is immutable
不過這個錯誤很好解決,直接給方法前面加上一個mutating
就能夠了。
雖然這種方法可以直接編譯經過,不過你會發現,當咱們的類實現Protocol的時候,咱們並不能調用到extensionFun
方法,依然會報Cannot assign to property: 'self' is immutable
錯誤,也就是說,必需要mutable
的方法才能調用被mutating
修飾的方法。
在子類中沒法使用父類中的方法,這顯然和Java中的抽象類不符,因此咱們須要換一種方法來實現實體方法
到底該如何作呢,其實只須要在Protocol後面加上 : class
就能夠了,這是用來限定協議只能應用在class上面,加上這個參數以後,咱們就能夠在擴展出來的方法中爲抽象屬性賦值了。segmentfault
protocol AbstractClass : class{}
爲Protocol實現實體屬性,這個比較簡單,和爲已有類擴展屬性是同樣的,能夠參考個人文章Swift快速爲類擴展屬性,就能夠很是輕鬆的聲明一個實體屬性。學習
var noNeedImplementProperty : String{ get{ return get0() } set{ set0(newValue)} }
最後咱們來看一個簡單的抽象類的完整代碼this
protocol AbstractProtocol : class , Property{ var mustImplementProperty : String{get set} func mustImplementFun() } extension AbstractProtocol{ var noNeedImplementProperty : String{ get{ return get0() } set{ set0(newValue)} } func noNeedImplementFunction() { print("this is a noNeedImplementFunction") self.noNeedImplementProperty = "[set in noNeedImplementFunction]" print("I can use noNeedImplementProperty,this property value is : \(self.noNeedImplementProperty)") self.mustImplementProperty = "[set in noNeedImplementFunction]" print("I can use mustImplementProperty,this property value is : \(self.noNeedImplementProperty)") } } class Test: AbstractProtocol { var mustImplementProperty: String = "" func mustImplementFun() { print("this is a mustImplementFun") self.noNeedImplementProperty = "[set in mustImplementFun]" print("I can use noNeedImplementProperty,this property value is : \(self.noNeedImplementProperty)") self.mustImplementProperty = "[set in mustImplementFun]" print("I can use mustImplementProperty,this property value is : \(self.noNeedImplementProperty)") } }
Android程序員在學習IOS的過程當中,確定會有不少思想禁錮,有不少Android裏面有的東西IOS裏面是沒有的,不過咱們能夠儘可能想辦法去實現。其實,最好的辦法是去接受IOS裏面的一些思想,多看別人寫的代碼,可以獲得一些啓發。code