[Swift] mutating 키워드란? (값 타입 인스턴스에서의 값 수정)

2024. 11. 17. 09:07·[Programming Language]/[Swift]

1. 값 타입 인스턴스 : 구조체(struct), 열거형(enum)

Swift에서 구조체와 열거형은 값 타입이고, 클래스는 참조 타입이다.

 

1-1. class : 참조 타입

참조 타입의 클래스의 인스턴스가 있을 때 값을 수정하는 메서드는 다른 프로그래밍 언어에서 했던 것처럼 하면 된다.

class Account {
    private var balance: Int = 0
    
    func getBalance() {
        print("잔고: \(balance)")
    }
    
    func deposit(_ amount: Int) {
        balance += amount
    }
    
    func withdraw(_ amount: Int) {
        balance -= amount
    }
}

var account = Account()
account.getBalance() // 잔고: 0

account.deposit(100)
account.getBalance() // 잔고: 100

account.withdraw(50)
account.getBalance() // 잔고: 50

 

 

1-2. struct, enum : 값 타입

그러나 값 타입인 구조체와 열거형에서는 다음과 같은 오류가 발생한다.

값 타입인 구조체로 선언된 Account의 프로퍼티 balance는 기본적으로 메서드 내에서 수정될 수 없다. 

 

 

2. mutating 키워드

이를 가능하게 만들어 주는 것이 바로 mutating 키워드다. 메서드 앞에 mutating 키워드를 사용하게 되면 메서드 내에서 프로퍼티 값이 수정될 수 있게 된다.

 


값 타입, 참조 타입...

Swift는 정말 엄격하고, 애플스러운(?) 것 같다...🫠

 

끝!

저작자표시 비영리 (새창열림)

'[Programming Language] > [Swift]' 카테고리의 다른 글

[Swift] Queue 자료 구조 (removeFirst를 popLast로 대체하기)  (0) 2024.11.16
[Swift] 메서드(Methods) [인스턴스•타입 메서드, mutating, self]  (1) 2024.11.07
[Swift] 프로퍼티 관찰자(Property Observers)  (0) 2024.11.06
[Swift] 프로퍼티(Property) [Stored •Computed, getter, setter, read-only]  (8) 2024.11.05
[Swift] 구조체(Structure) vs 클래스(Class) 차이점  (4) 2024.11.04
'[Programming Language]/[Swift]' 카테고리의 다른 글
  • [Swift] Queue 자료 구조 (removeFirst를 popLast로 대체하기)
  • [Swift] 메서드(Methods) [인스턴스•타입 메서드, mutating, self]
  • [Swift] 프로퍼티 관찰자(Property Observers)
  • [Swift] 프로퍼티(Property) [Stored •Computed, getter, setter, read-only]
Semincolon
Semincolon
It seems small, that semicolon is a big deal.
  • Semincolon
    Semincolon
    Semincolon
  • 전체
    오늘
    어제
    • 분류 전체보기 (87) N
      • [Programming Language] (73) N
        • [JSP] (1) N
        • [Swift] (23)
        • [SwiftUI] (16)
        • [Python] (22)
        • [C언어] (6)
        • [Kotlin] (4)
        • [C#] (1)
      • [Frame Work] (5)
        • [Flutter] (4)
        • [Spring Boot] (1)
      • [Projects] (3)
        • [Android][Kotlin] 공유 캘린더(20.. (1)
        • [Unity] 인내의 숲(2024.03) (2)
      • Today's Learning (5)
      • [ETC] (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
Semincolon
[Swift] mutating 키워드란? (값 타입 인스턴스에서의 값 수정)
상단으로

티스토리툴바