Swift protocol協議
阿新 • • 發佈:2019-01-06
在Swift裡協議裡可以定義屬性,方法
可以看出,雖然Dog類實現了Pet協議,但協議規定的只讀屬性發生了改變。
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 = "" }