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/322099.html