Swift学习

Swift 5.x 关键字 mutating 的作用

2020-07-02  本文已影响0人  ShenYj
1. 在实例方法中修改属性
struct Point {
    var x = 0.0, y = 0.0
    mutating func moveBy(x deltaX: Double, y deLtaY: Double) {
        x += deltaX
        y += deLtaY
    }
}

var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveBy(x: 2.0, y: 2.0)
print("The point is now at (\(somePoint.x), \(somePoint.y))")

输出结果:

The point is now at (3.0, 3.0)

如果在方法前没有加mutating修饰, 那么在修改属性的位置就会报错:
Left side of mutating operator isn't mutable: 'self' is immutable

2. 在mutating方法中赋值给self

e.g.

struct Point {
    var x = 0.0, y = 0.0
    mutating func moveBy(x deltaX: Double, y deLtaY: Double) {
        self = Point(x: 3.0, y: 3.0)
    }
}
3. 枚举的mutating 方法

e.g.

enum TriStateSwitch {
    case off, low, high
    
    mutating func next() {
        switch self {
        case .off:
            self = .low
        case .low:
            self = .high
        case .high:
            self = .off
        }
    }
}

var ovenLight = TriStateSwitch.low
ovenLight.next()
ovenLight.next()

print(ovenLight)

输出结果:

off
上一篇下一篇

猜你喜欢

热点阅读