在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è)簡單的例子,假如定義一個(gè)點(diǎn)結(jié)構(gòu)體,該結(jié)構(gòu)體有一個(gè)修改點(diǎn)位置的實(shí)例方法:(編譯器會(huì)報(bào)錯(cuò))
struct Point { var x = 0, y = 0 func moveXBy(x: Int, 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í)例方法中修改屬性值,而且提示你要加mutating關(guān)鍵字。
為了能夠在實(shí)例方法中修改屬性值,可以在方法定義前添加關(guān)鍵字mutating,修改后的代碼:
struct Point { var x = 0, y = 0 mutating func moveXBy(x: Int, y: Int) { self.x += x self.y += y }}另外,在值類型的實(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 .High ovenLight.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)情況下就可以修改屬性值,不存在以上問題。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注