Skip to content

Latest commit

ย 

History

History
74 lines (57 loc) ยท 2.2 KB

mutating.md

File metadata and controls

74 lines (57 loc) ยท 2.2 KB

mutating ํ‚ค์›Œ๋“œ์— ๋Œ€ํ•ด ์„ค๋ช…ํ•˜์‹œ์˜ค.

์ฐธ๊ณ ํ•œ ์ข‹์€ ๊ธ€

์—ฐ๊ด€๋œ ๋‹ต๋ณ€

Answer

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