Protocol Extension 協議擴展

// 原始協議

protocol MyProtocol {

func method()

}

// 對原有協議進行擴展實現。 通過提供 protocol 的 extension, 我們為 protocol 提供了默認實現,相當于將 protocol 中的方法設定為了 optional

extension MyProtocol {

func method(){

print("Called")

}

}

// 這個結構體實現了 MyProtocol 協議

struct MyStruct: MyProtocol {

}

MyStruct().method()? // 輸出 Called

protocol A2 {

func method1() -> String

}

// 對協議進行原有的方法進行擴展并實現,并且添加了一個方法并實現

extension A2 {

func method1() -> String {

return "hi"

}

func method2() -> String {

return "hi"

}

}

struct B2: A2 {

func method1() -> String {

return "hello"

}

func method2() -> String {

return "hello"

}

}

let b2 = B2()

b2.method1()? ? ? //? hello

b2.method2()? ? ? //? hello

let a2 = b2 as A2

a2.method1()? ? ? //? hello

a2.method2()? ? ? //? hi

/*

如果類型推斷得到的是實際的類型

> 那么類型的實現將被調用,如果類型中沒有實現的方法,那么協議擴展中的默認實現將被調用

如果類型推斷得到的是協議,而不是實際類型

> 并且方法在協議中進行了定義,那么類型中的實現將被調用。如果類型中沒有實現,那么協議擴展中的默認實現將被調用

> 否則(也就是方法沒有在協議中定義),擴展中的默認實現將被調用 (輸出 hi)

*/

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容