본문 바로가기

문법

[작성중...] What is the Mutating ?

- Reference

- https://medium.com/mobile-app-development-publication/use-swift-struct-for-total-immutability-6f07388cad5e

 

Use Swift Struct For Total Immutability

The many ways to prevent mutability of Swift’s struct

medium.com

 

mutating 이란?

- 값 타입(구조체, 열거형)의 메서드내부 프로퍼티의 변수를 변경할 수 있다는 것컴파일러에게 알려주는 것이다. 

   var struct 변수에서만 호출할 수 있지만 let struct 변수에서는 호출할 수 없다.

class A {
    var value = 10
}
let a = A()

a.value = 20 // okay, can stil mutate it even a is let
"""
It's the because class are reference type, only the memory location is immutable,
but the content mutability is independent from it.
=> 클래스가 참조 유형이기 때문에 메모리 위치만 변경할 수 있지만 내용 변경 가능성은 독립적입니다.
"""

// However, for struct, it is an error.

struct B {
    var value = 10
}
let b = B()
//b.value = 20 // Can't assign to property: 'a' is a 'let' constant

// MARK: Copy by Value prevent accidental change
// 클래스는 변수에 값을 할당하면 기존에 참조를 할당하는 변수와 공유한다.

class Aclass { var value = 0 }

let classA = Aclass()
var classB = classA
classB.value = 1
print("\(classB.value) and \(classA.value)") // 1 and 1

// 하지만 struct인 구조체는 다르다. 변수에 새로운 값을 할당하면 값이 복사가된다. 각각 독립적이다.

struct Astruct { var value = 0 }
let structA = Astruct()
var structB = structA
structB.value = 1
print("\(structA.value) \(structB.value)") // result is 0 1

값타입과 참조타입의 메모리 저장 방식


// 멤버 VAR은 내부 변경 함수에 의해서만 변경될 수 있습니다.
struct ABC {
    var value = 10
    
    func changeValue() {
        value += 10 //Error
    }
    // callChangeValue메서드 내부에있는 changeValue메서드 또한 내부의 프로퍼티 값을 변경하기떄문에 mutating을 써준다.
    mutating func callChangeValue() {
        changeValue()
    }
}

// mutating 키워드는 컴파일러가 함수가 내부 변수를 변경하고 있다는 것을 쉽게 알 수 있도록 하는 데 사용되므로 var struct 변수에서만 호출할 수 있지만 let struct 변수에서는 호출할 수 없습니다.
struct ABC2 {
    var value = 10
    mutating func changeValue() { value += 10 }
}
var x = ABC2()
x.changeValue()
let y = ABC2()
y.changeValue() // Error

// let 상수는 mutating 함수를 호출하는 것을 방지함으로써 struct가 돌연변이되지 않도록 하는 데 도움이 됩니다.

 

왜 값 타입의 프로퍼티의 값이 변경될 수 있다는것을 컴파일러에게 알려줘야할까? 컴파일러는 그것을 말해주지 않으면 모르니깐 참조타입과 구분되는 값타입에게는 알려줘야하는걸까 ?

 

값이 변하면 안되는것인가? 음.. 내일 더 깊이 궁금증을 해결해보자