关键字 mutating 的作用
优质
小牛编辑
136浏览
2023-12-01
Swift 5.x 关键字 mutating 的作用
1. 在实例方法中修改属性
- 结构体和枚举是值类型. 默认情况下, 值类型属性不能被自身的实例方法修改.
可以选择在
func
关键字前加上mutating
关键字来指定实例方法内可以修改属性e.g.
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
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
方法
枚举的
mutating
方法可以设置隐含的self
属性为相同枚举里的不同成员, 与结构体类似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