페이지

2017년 2월 17일 금요일

Swift mutating

Modifying Value Types from Within Instance Methods Structures and enumerations are value types. By default, they cannot be modified from within its instance Methods However, if you want, you can opt in to "mutating" keyword. mutating The mutating keyword is added to its definition to enable it to modify its properties.


struct RectST {
    var x : Double = 0
    func minus(x dx:Int ){
       x -= dx     error: Left side of mutating operator isn't mutable: 'self' is immutable
    }
    mutating func move (x dx:Double){
        x += dx
    }
    mutating func moveSelf(x dx:Double){
        self = RectST(x:dx)
    }
}

class Rect {
    var x : Double = 0
    func move (x dx:Double){
        x += dx
    }
}

var c01 = RectST()
c01.minus(x:3)
c01.move(x:222) 

enum TriStateSwitch {
    case off,low,high
    mutating func next(){
        switch self {
            case .off:
                self = .low
            case .low:
                self = .high
            case .high:
                self = .off
                
        }
    }

}

댓글 없음:

댓글 쓰기