티스토리 뷰

Swift

mutating 키워드에 대해 알아보기

진태우 2018. 6. 11. 17:29
인스턴스 메서드 안에서 value type 변경

struct 및 enum은 value type 입니다. 
기본적으로 value type은 인스턴스 메서드 안에서 변경이 불가합니다.

하지만 선택적으로 mutating 키워드를 붙인 메서드에서는 원하는 프로퍼티를 수정할 수 있습니다. 
struct Point { 
    var x = 0.0, y = 0.0 
    mutating func moveBy(x deltaX: Double, y deltaY:Double) {   
        x += deltaX   // mutating function 이기 때문에 성공 
        y += deltaY 
    } 
} 

var somePoint = Point(x: 1.0, y: 1.0) // (1.0, 1.0) 
somePoint.moveBy(x: 2.0, y: 3.0) // (3.0, 4.0) 
print("The point is now at (\(somePoint.x), \(somePoint.y))”)
// Prints "The point is now at (3.0, 4.0)"

또한 mutating 키워드와 상관없이 let으로 선언된 프로퍼티 변경은 불가합니다.

let fixedPoint = Point(x: 3.0, y: 3.0) 
fixedPoint.moveBy(x: 2.0, y: 3.0)    // error


mutating 메서드에서 self 할당

mutating 메서드는 새로운 인스턴스를 self 속성에 할당할 수 있습니다.

self 속성에 새로운 인스턴스를 할당하는 것은 struct, enum에만 가능합니다.
struct Point { 
    var x = 0.0, y = 0.0 
    mutating func moveBy(x deltaX: Double, y deltaY:Double) { 
        self = Point(x: x + deltaX, y: y + deltaY) 
    } 
} 

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 is now equal to .high 
ovenLight.next() 
// ovenLight is now equal to .off"


Mutating keyword - ios 문서


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함