[Swift] 프로퍼티 관찰자(Property Observers)

2024. 11. 6. 08:41·[Programming Language]/[Swift]

1. 프로퍼티 관찰자

프로퍼티 관찰자란 프로퍼티의 값이 변경될 때 호출되는 것으로, 새로운 값이 기존 값과 동일하더라도 호출된다.

 

프로퍼티 관찰자에는 2가지 종류가 있다.

  • willSet : 새로운 값으로 변경되기 전에 호출
  • didSet : 새로운 값으로 변경되고 나서 호출

1-1. willSet

class Asset {
    var totalMoney: Int = 0 {
        willSet(newTotalMoney) {
            print("새로운 잔액 : \(newTotalMoney)만원")
        }
    }
}

let asset = Asset()
asset.totalMoney = 100 // 새로운 잔액 : 100만원

위 예제에서 willSet은 asset.totalMoney = 100 부분에서 값의 변경이 이뤄지기 전에 호출된다. 이때 변경될 새로운 값을 newTotalMoney라는 파라미터로 받고 있는데 이를 설정하지 않으면 newValue로 사용할 수 있다.

willSet {
	print("새로운 잔액 : \(newValue)만원")
}

 

1-2. didSet

class Asset {
    var totalMoney: Int = 0 {
        willSet {
            print("새로운 잔액 : \(newValue)만원")
        }
        
        didSet(oldTotalMoney) {
            if totalMoney >= oldTotalMoney {
                print("수익 : \(totalMoney - oldTotalMoney)만원")
            } else {
                print("손해 : \(oldTotalMoney - totalMoney)만원")
            }
        }
    }
}

let asset = Asset()

asset.totalMoney = 100 // 새로운 잔액 : 100만원, 수익 : 100만원
print()

asset.totalMoney = 50 // 새로운 잔액 : 50만원, 손해 : 50만원

앞선 예제에 didSet 관찰자가 추가되었다. 이는 값의 변경이 이뤄지고 나서 호출되고 변경되기 전의 값을 oldTotalMoney라는 파라미터로 받고 있다. willSet과 마찬가지로 별도의 이름을 정하지 않으면 oldValue로 사용할 수 있다.

didSet {
    if totalMoney >= oldValue {
        print("수익 : \(totalMoney - oldValue)만원")
    } else {
        print("손해 : \(oldValue - totalMoney)만원")
    }
}

 

 

2. 상속한 하위 클래스에서의 프로퍼티 관찰자 재정의

상위 클래스를 상속한 하위 클래스에서 상위 클래스의 프로퍼티에 대한 프로퍼티 관찰자를 정의할 수 있다. 이는 상위 클래스의 프로퍼티가 저장된 프로퍼티인지, 계산된 프로퍼티인지에 관계없이 가능하다.

class Vehicle {
    var maxSpeed: Int = 100
}

class Car: Vehicle {
    override var maxSpeed: Int {
        willSet {
            print("새로운 속도 : \(newValue)")
        }
        
        didSet {
            print("속도 변화 : \(maxSpeed - oldValue)")
        }
    }
}

let c = Car()

c.maxSpeed = 200

// 새로운 속도 : 200
// 속도 변화 : 100

 

그러나 만약 상위 클래스의 프로퍼티가 변수가 아닌 상수(Constant)라면 값이 변경될 일이 없으므로 프로퍼티 관찰자를 재정의할 수 없다.

 


끝!

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

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

[Swift] Queue 자료 구조 (removeFirst를 popLast로 대체하기)  (0) 2024.11.16
[Swift] 메서드(Methods) [인스턴스•타입 메서드, mutating, self]  (1) 2024.11.07
[Swift] 프로퍼티(Property) [Stored •Computed, getter, setter, read-only]  (8) 2024.11.05
[Swift] 구조체(Structure) vs 클래스(Class) 차이점  (4) 2024.11.04
[Swift] ~= 연산자 : 범위 확인 연산자, 패턴 매치 연산자  (0) 2024.10.24
'[Programming Language]/[Swift]' 카테고리의 다른 글
  • [Swift] Queue 자료 구조 (removeFirst를 popLast로 대체하기)
  • [Swift] 메서드(Methods) [인스턴스•타입 메서드, mutating, self]
  • [Swift] 프로퍼티(Property) [Stored •Computed, getter, setter, read-only]
  • [Swift] 구조체(Structure) vs 클래스(Class) 차이점
Semincolon
Semincolon
It seems small, that semicolon is a big deal.
  • Semincolon
    Semincolon
    Semincolon
  • 전체
    오늘
    어제
    • 분류 전체보기 (133)
      • [Programming Language] (78)
        • [JSP] (6)
        • [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)
      • [DB] (15)
        • - Oracle (15)
      • [Programmers] (25)
        • - SQL (25)
      • [ETC] (2)
      • Today's Learning (5)
  • 블로그 메뉴

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

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
Semincolon
[Swift] 프로퍼티 관찰자(Property Observers)
상단으로

티스토리툴바