Swift protocol协议

前端之家收集整理的这篇文章主要介绍了Swift protocol协议前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Swift里协议里可以定义属性方法
protocol Pet {
    
    var name: String {get set}
    var birthPlace: String {get}
    func playWith()
    func fed()
    
    mutating func changeName(name: String)
}

struct Dog: Pet {
    
    internal mutating func changeName(name: String) { // 结构体加上mutating
        self.name = name
    }

    
    var name: String = "dog"
    var birthPlace: String = "china"
    
    func fed() {
        print("fed me")
    }

    internal func playWith() {
        print("play with me")
    }
}

协议里定义的方法属性要全部实现

var dog:Dog = Dog()
dog.birthPlace = "beijing"

var pet:Pet = Dog()
pet.birthPlace = "beijing"
再看上面的代码,前两行声明一个Dog类型的实例,可以修改其birthPlace,后面两行声明的是一个Pet类型的实例,不能修改其birthPlace,因为在Pet协议里birthPlace是只读的
可以看出,虽然Dog类实现了Pet协议,但协议规定的只读属性发生了改变。


协议里声明构造函数

protocol Pet {
    
    var name: String {get set}
    var birthPlace: String {get}
    func playWith()
    func fed()
    init(name: String)
    mutating func changeName(name: String)
}

class Animal {
    var legs: Int = 4
    var name: String = "i am a animal"
    init(name: String) {
        self.name = name
    }
}

class Bird: Animal,Pet {
    override required init(name: String) { // override关键字 对应 父类animal,required 对应协议Pet
        super.init(name: name)
    }

    internal func changeName(name: String) {
        
    }

    internal func fed() {
        
    }

    internal func playWith() {
        
    }

    internal var birthPlace: String = ""
}

猜你在找的Swift相关文章