1.protocol中的方法參數(shù)不能有默認(rèn)值
protocol Eatable {
//func eat(foodName:String = "大米") //報錯
func eat(foodName:String) //正確
}
2.遵從protocol的class 或者 struct需要實現(xiàn)其中的方法,否則會報錯
class Person:Eatable{
func eat(foodName: String) {
}
}
struct Pig:Eatable{
func eat(foodName: String) {
}
}
3.protocol中還可以聲明變量源请,遵從的class必須有這樣的變量或者getter setter方法
protocol Eatable{
var foodName : String {get set}
var eatMethod : String { get }
func eat()
}
class Person : Eatable{
var foodName: String = "大米"
var eatMethod: String = "用嘴吃"
func eat() {
}
}
eatMethod 還可以這樣實現(xiàn)
class Person : Eatable{
private var innerEatMethod = "用嘴吃"
var eatMethod: String {
get {
return innerEatMethod
}
}
var foodName: String = "大米"
func eat() {
}
}
4.一個protocol可以繼承另外一個protocol
protocol EatDrinkable : Eatable {
var drinkMethod : String {get set}
func drink()
}
class Person : EatDrinkable{
var foodName: String = "上海記憶酸奶"
var eatMethod: String = "用嘴吃"
var drinkMethod: String = "用嘴喝"
func eat() {
}
func drink() {
}
}
5.一個類可以遵從多個協(xié)議
protocol Runable {
func run ()
}
protocol Jumpable {
func jump()
}
class Person : Runable,Jumpable{
func jump() {
}
func run() {
}
}