swift中mutating的作用?


swift中协议是可以被Struct和enum实现的,mutating关键字是为了能在被修饰的函数中修改struct或enum的变量值。对Class完全透明。

struct Point {
    var x = 0
    var y = 0
    
    mutating func movePoint(x: Int, y: Int) {
        self.x += x
    }
}
enum TriSwitch {
    case Off, Low, High
    mutating func next() {
        switch self {
        case .Off:
            self = .Low
        case .Low:
            self = .High
        case .High:
            self = .Off
        }
    }
}