//: 在实例方法中修改值类型(Modifying Value Types from Within Instance Methods) //: 结构体和枚举是值类型。一般情况下,值类型的属性不能在它的实例方法中被修改。但是,如果你确实需要在某个特定的方法中修改结构体或者枚举的属性,你可以选择变异(mutating)这个方法,然后方法就可以从方法内部改变它的属性;并且它做的任何改变在方法结束时还会保留在原始结构中。方法还可以给它隐含的self属性赋值一个全新的实例,这个新实例在方法结束后将替换原来的实例。 structPoint { var x =0.0, y =0.0 mutatingfuncmoveByX(deltaX: Double, ydeltaY: Double) { x += deltaX y += deltaY } }
var somePoint =Point(x: 3.0, y: 3.0) somePoint.moveByX(2.0, y: 3.0)
//: 在可变方法中给 self 赋值(Assigning to self Within a Mutating Method) structPoint1 { var x =0.0, y =0.0 mutatingfuncmoveByX(deltaX: Double, ydeltaY: Double) { self=Point1(x: x + deltaX, y: y + deltaY) } } //: 这里不仅仅学习一个语法,而是思考为什么费劲把默认不可变的枚举变成可变,是因为提供一个可能结合枚举特性,写出简洁表达能力强的代码。 //: Ash Furrow: Ideas vs Syntax. Watch video here: https://youtu.be/YsUTuwpbURA enumTriStateSwitch { caseOff, Low, High mutatingfuncnext() { switchself { caseOff: self=Low caseLow: self=High caseHigh: self=Off } } }
var ovenLight =TriStateSwitch.Low ovenLight.next() ovenLight.next() //: 类型方法 (Type Methods)
classPlayer { var tracker =LevelTracker() let playName: String funccompeletedLevel(level: Int) { LevelTracker.unlockLevel(level +1) tracker.advanceToLevel(level +1) } init(name:String) { playName = name } }
var player =Player.init(name: "Will") player.compeletedLevel(4) print(LevelTracker.highestunlockedLevel)
player =Player.init(name: "Ge") if player.tracker.advanceToLevel(6) { print("Level 6 has been unlocked.") } else { print("Level 6 has not yet been unlocked.") }