Mutating 이 뭔데

Zion·2021년 12월 12일
1

mutaing 에 대해서 읽어보고 정리해봤습니다.
출처 : docs.swift

Modifying Value from Within Instance Methods

define mutable

mutable은 '변하기 쉬운'이라는 뜻이다

Structures and enumerations are value types. By default, the properties of a value type can't be modified from within its instance methods.

→ Structure 및 Enumeration은 값 유형입니다. 기본적으로 값 유형의 속성은 instance method 내에서 수정할 수 없습니다.

However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for the method. The method can then mutate ( that is, change) its properties from within the method, and any changes that it makes are written back to the original structure when the method ends. The method can also assign a completely new instance to its implicit self property, and this new instance will replace the existing one when the method ends.

→ 그러나 특정 메서드 내에서 Structure 또는 Enumeration의 속성을 수정해야 하는 경우 해당 메서드에 대한 동작을 변경할 수 있습니다. 그런 다음 메소드는 메소드 내에서 속성을 변경(변경)할 수 있으며, 메소드가 종료되면 모든 변경 내용이 원래 구조에 다시 기록됩니다. 메서드는 암시적 자체 속성에 완전히 새 인스턴스를 할당할 수도 있으며, 이 새 인스턴스는 메서드가 종료될 때 기존 인스턴스를 대체합니다.

... 이게 무슨말 이야 할 수 있다!. 그래서 playground를 켜봤다.

기본적으로 값 유형의 속성은 instance method 내에서 수정할 수 없습니다.

맞네. var이라도 instance method 안에서 수정이 안된다.

오류 문구를 자세히 볼까


Left side of mutating operator isn't mutable. += operator 왼쪽 부분이 mutable 하지 않다고 한다.

fix를 눌러서 고쳐봤다

Usage

Enumeration을 위한 Mutating method

Mutating methods for enumerations can set the implicit self parameter to be a different case from the same enumeration.

enum TrsStateSwitch {
    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

정리

method 앞에 붙어있는mutating 이라 함은. value type instance(e.g Structure, Enumeration) 의 method로 instance property 값을 change 하게 해 주는 것이다.

profile
어제보다만 나아지는

0개의 댓글