mutate
: ๋ณํํ๋ค, ๋ณํ์ํค๋ค.
๋ฌด์์ ๋ณํ์ํค๋๊ฑฐ๋๋ฉด ๋ฐ๋ก value type์ด๋ค. ๊ธฐ๋ณธ์ ์ผ๋ก value type(struct, enum)์ property๋ค์ ์ธ์คํด์ค ๋ฉ์๋์ ์ํด ์์ ๋ ์ ์๋ค.
ํ์ง๋ง ์ธ์คํด์ค ๋ฉ์๋ ์์ mutating
์ด๋ผ๋ ํค์๋๋ฅผ ๋ถ์ธ๋ค๋ฉด ์ด์ผ๊ธฐ๊ฐ ๋ฌ๋ผ์ง๋ค.
mutating
์ ์ ์ธํ ๋ฉ์๋๋ ๋ฉ์๋ ๋ด์์ property๋ฅผ ๋ณ๊ฒฝํ ์ ์๊ณ , ๋ฉ์๋๊ฐ ์ข
๋ฃ๋ ๋ ๋ณ๊ฒฝํ ๋ชจ๋ ๋ด์ฉ์ ๊ธฐ์กด value type property์ ๋ค์ ๊ธฐ๋กํ๋ค.
-
struct
struct Point { var x = 0.0, y = 0.0 mutating func moveBy(x deltaX: Double, y deltaY: Double) { x += deltaX y += deltaY } } var somePoint = Point(x: 1.0, y: 1.0) print("The point is now at (\(somePoint.x), \(somePoint.y))") // Prints "The point is now at (1.0, 1.0)" somePoint.moveBy(x: 2.0, y: 3.0) print("The point is now at (\(somePoint.x), \(somePoint.y))") // Prints "The point is now at (3.0, 4.0)"
-
enum
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 == .high ovenLight.next() // ovenLight == .off
ํ์ง๋ง let์ผ๋ก ์ ์ธ๋ ์ธ์คํด์ค๋ property๊ฐ ๋ณ์์ด๋๋ผ๋ ์์ฑ์ ๋ณ๊ฒฝํ ์ ์๊ธฐ ๋๋ฌธ์ mutating ๋ฉ์๋๋ฅผ ํธ์ถํ ์ ์๋ค.
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
let somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveBy(x: 2.0, y: 3.0) // error: cannot use mutating member on immutable value: 'somePoint' is a 'let' constant