1.通過擴展采納協(xié)議
// 定義一個Animal協(xié)議
protocol Animal{
var getName:String{get}
}
// 定義一個Dog類,但是沒有采納Animal協(xié)議
class Dog{
func shout() -> String{
return "汪汪汪"
}
}
// 通過擴展采納并實現(xiàn)Animal協(xié)議
extension Dog:Animal{
var getName:String{
return "泰迪"
}
}
let dog = Dog()
print("狗的叫聲\(dog.shout())")
print("狗的名字\(dog.getName)")
2.通過空擴展采納協(xié)議
當(dāng)一個類型已經(jīng)符合了每個協(xié)議中的所有要求,卻沒有聲明采納該協(xié)議時歇攻,類型并不會自動采納協(xié)議,此時圃验,可以通過一個實現(xiàn)體為空的擴展(即空擴展)來采納該協(xié)議
protocol Getname{
var getName:String{get}
}
// 定義一個Student結(jié)構(gòu)體
struct Student {
var name:String
var getName:String{
return "這個學(xué)生的名字是\(name)"
}
}
extension Student:Getname{}
let people = Student(name:"小明")
print(people.getName)
let student:Getname = people
print(student.getName)
3.協(xié)議的擴展
protocol People{
func drink() -> String
}
// 擴展新增方法并實現(xiàn)掉伏,此時必須實現(xiàn)
extension People{
func eat() -> String {
return "吃骨頭"
}
func legs() -> Int {
return 2
}
}
class Teacher: People {
func drink() -> String {
return "喝水"
}
}
let teacher = Teacher()
print(teacher.drink())
print(teacher.eat())
print("人類\(teacher.legs())條腿")