在 ** swift ** 中捶箱,包含三種類型(type): ** structure ** , ** enumeration ** , ** class **
其中structure和enumeration是值類型( ** value type ** ),class是引用類型( ** reference type ** )
但是與objective-c不同的是磁奖,structure和enumeration也可以擁有方法(method),其中方法可以為實(shí)例方法(instance method),也可以為類方法(type method),實(shí)例方法是和類型的一個(gè)實(shí)例綁定的。
在swift官方教程中有這樣一句話:
“Structures and enumerations are value types.
By default, the properties of a value type cannot be modified from within its instance methods.”
摘錄來自: Apple Inc. “The Swift Programming Language”。 iBooks. https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewBook?id=881256329
大致意思就是說析苫,雖然結(jié)構(gòu)體和枚舉可以定義自己的方法,但是默認(rèn)情況下穿扳,實(shí)例方法中是不可以修改值類型的屬性衩侥。
舉個(gè)簡(jiǎn)單的例子,假如定義一個(gè)點(diǎn)結(jié)構(gòu)體矛物,該結(jié)構(gòu)體有一個(gè)修改點(diǎn)位置的實(shí)例方法:
struct Point {
var x = 0, y = 0
func moveXBy(x:Int,yBy y:Int) {
self.x += x
// Cannot invoke '+=' with an argument list of type '(Int, Int)'
self.y += y
// Cannot invoke '+=' with an argument list of type '(Int, Int)'
}
}
編譯器拋出錯(cuò)誤茫死,說明確實(shí)不能在實(shí)例方法中修改屬性值。
為了能夠在實(shí)例方法中修改屬性值履羞,可以在方法定義前添加關(guān)鍵字 ** mutating **
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)
另外峦萎,在值類型的實(shí)例方法中,也可以直接修改self屬性值忆首。
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.LowovenLight.next()
// ovenLight is now equal to .HighovenLight.next()
// ovenLight is now equal to .Off”
TriStateSwitch枚舉定義了一個(gè)三個(gè)狀態(tài)的開關(guān)爱榔,在next實(shí)例方法中動(dòng)態(tài)改變self屬性的值。
當(dāng)然糙及,在引用類型中(即class)中的方法默認(rèn)情況下就可以修改屬性值详幽,不存在以上問題。