不能在結(jié)構(gòu)體類型的常量(a constant of structure type)上調(diào)用可變方法,因為其屬性不能被改變,即使屬性是變量屬性。
struct Point {
var x = 0.0, y = 0.0
func isToTheRightOfX(x: Double) -> Bool {
return self.x > x // 如果不使用self前綴,Swift 就認為兩次使用的x都指的是名稱為x的函數(shù)參數(shù)。
}
mutating func moveByX(deltaX: Double, y deltaY: Double) {
// x += deltaX
// y += deltaY // 改屬性
self = Point(x: x + deltaX, y: y + deltaY) // 該實例本身
}
}
var somePoint = Point(x: 4.0, y: 5.0)
if somePoint.isToTheRightOfX(1.0) {
print("This point is to the right of the line where x == 1.0")
}
// 打印輸出: This point is to the right of the line where x == 1.0
somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveByX(2.0, y: 3.0)
print("The point is now at (\(somePoint.x), \(somePoint.y))")
// 打印輸出: "The point is now at (3.0, 4.0)"
枚舉的可變方法可以把self設(shè)置為同一枚舉類型中不同的成員:
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 現(xiàn)在等于 .High
ovenLight.next()
// ovenLight 現(xiàn)在等于 .Off