搜索
您的当前位置:首页正文

(二十五)[Swift]Protocol的基本用法

来源:知库网

1.protocol中的方法参数不能有默认值

protocol Eatable {
    //func eat(foodName:String = "大米") //报错
    func eat(foodName:String) //正确
}

2.遵从protocol的class 或者 struct需要实现其中的方法,否则会报错

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 还可以这样实现

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.一个类可以遵从多个协议

protocol Runable {
    func run ()
}
protocol Jumpable {
    func jump()
}
class Person : Runable,Jumpable{
    func jump() {
        
    }
    func run() {
        
    }
}
Top