Swift关键字之 mutating

在 swift 中,包含三种类型(type):structure,enumeration,class

其中 structure 和 enumeration 是值类型 (value type),class 是引用类型(reference type)

在 structure 和 enumeration 中也可以拥有方法(method),其中方法可以为实例方法(instance method)和类方法(type method),实例方法和类型的一个实例绑定。

Structures and enumerations are value types.
By default, the properties of a value type cannot be modified from within its instance methods.”(结构体和枚举是值类型,默认的,值类型的属性不能在他们的实例方法中被更改。)

举例:

1
2
3
4
5
6
7
8
struct Point {
var x = 0, y = 0

func moveXBy(x:Int,yBy y:Int) {
self.x += x
self.y += y
}
}

编译器会报错

那么想要在值类型的实例方法中修改其属性是否可行呢?

这时,我们就要用到 mutating 关键字了

1
2
3
4
5
6
7
8
9
10
11
12
struct Point {
var x = 0, y = 0

mutating func moveXBy(x:Int,yBy y:Int) {
self.x += x
self.y += y
}
}

var p = Point(x: 5, y: 5)

p.moveXBy(3, yBy: 3)

另外,在值类型的实例方法中也可以修改 self 的属性值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 is now equal to .High
ovenLight.next()
// ovenLight is now equal to .Off”

在 class 类型中不存在上述问题,可以随意修改。

参考资料:The Swift Programming Language

文章作者: Ammar
文章链接: http://lizhaoloveit.cn/2015/07/08/Swift%E5%85%B3%E9%94%AE%E5%AD%97%E4%B9%8B-mutating/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Ammar's Blog
打赏
  • 微信
  • 支付宝

评论