首页 > 学院 > 开发设计 > 正文

Swift protocol协议

2019-11-08 00:15:07
字体:
来源:转载
供稿:网友
在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 = ""}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表