结构体和枚举是值类型,默认情况下,值类型的属性不能被自身的实例方法修改
在func关键字前面加mutating
可以允许这种修改行为
struct Point {
var x = 0.0, y = 0.0
func moveBy(deltaX: Double, deltaY: Double) {
x += deltaX // Left side of mutating operator isn't mutable: 'self' is immutable
y += deltaY // Left side of mutating operator isn't mutable: 'self' is immutable
}
}
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(deltaX: Double, deltaY: Double) {
x += deltaX
y += deltaY
}
}
enum StateSwitch {
case low, middle, high
func next() {
switch self {
case .low:
self = .middle // Cannot assign to value: 'self' is immutable
case .middle:
self = .high // Cannot assign to value: 'self' is immutable
case .high:
self = .low // Cannot assign to value: 'self' is immutable
}
}
}
enum StateSwitch {
case low, middle, high
mutating func next() {
switch self {
case .low:
self = .middle
case .middle:
self = .high
case .high:
self = .low
}
}
}
网友评论