// 原始協議
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)
*/