美文网首页
Swift将protocol的方法声明为mutating

Swift将protocol的方法声明为mutating

作者: TomatosX | 来源:发表于2017-07-17 22:28 被阅读68次

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修饰符的话,会编译不通过。

相关文章

网友评论

      本文标题:Swift将protocol的方法声明为mutating

      本文链接:https://www.haomeiwen.com/subject/jqaqkxtx.html