// 原始協(xié)議
protocol MyProtocol {
func method()
}
// 對原有協(xié)議進(jìn)行擴(kuò)展實(shí)現(xiàn)。 通過提供 protocol 的 extension, 我們?yōu)?protocol 提供了默認(rèn)實(shí)現(xiàn),相當(dāng)于將 protocol 中的方法設(shè)定為了 optional
extension MyProtocol {
func method(){
print("Called")
}
}
// 這個(gè)結(jié)構(gòu)體實(shí)現(xiàn)了 MyProtocol 協(xié)議
struct MyStruct: MyProtocol {
}
MyStruct().method()? // 輸出 Called
protocol A2 {
func method1() -> String
}
// 對協(xié)議進(jìn)行原有的方法進(jìn)行擴(kuò)展并實(shí)現(xiàn),并且添加了一個(gè)方法并實(shí)現(xiàn)
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
/*
如果類型推斷得到的是實(shí)際的類型
> 那么類型的實(shí)現(xiàn)將被調(diào)用,如果類型中沒有實(shí)現(xiàn)的方法,那么協(xié)議擴(kuò)展中的默認(rèn)實(shí)現(xiàn)將被調(diào)用
如果類型推斷得到的是協(xié)議,而不是實(shí)際類型
> 并且方法在協(xié)議中進(jìn)行了定義,那么類型中的實(shí)現(xiàn)將被調(diào)用。如果類型中沒有實(shí)現(xiàn),那么協(xié)議擴(kuò)展中的默認(rèn)實(shí)現(xiàn)將被調(diào)用
> 否則(也就是方法沒有在協(xié)議中定義),擴(kuò)展中的默認(rèn)實(shí)現(xiàn)將被調(diào)用 (輸出 hi)
*/