Swift将protocol的方法声明为mutating

2017-07-17  本文已影响68人  TomatosX

Swift的mutating关键字修饰方法是为了能在该方法中修改struct或是enum的变量

struct是不能在方法里随意的改变自己的成员变量的,所以必须要用mutating关键词来修饰。

class是不需要mutating修饰符,因为class可以随意更改自己的成员变量。

protocol Vehicle {
    var numberOfWheels: Int {get}
    var color: UIColor {get set}
    
    mutating func changeColor()
}

struct MyCar: Vehicle {
    var numberOfWheels: Int
    var color: UIColor = .blue
    
    mutating func changeColor() {
        color = .red
    }
}

如果不加mutating修饰符的话,会编译不通过。

上一篇 下一篇

猜你喜欢

热点阅读