프로퍼티 감시자
- 특징
- 프로퍼티의 값이 변할때, 동작을 수행한다
- 값이 바뀌기 직전에 호출되는 willSet
- 값이 바뀐 뒤에 호출되는 didSet
- 매개변수 이름이 지정되지 않았다면, 명시적으로 newValue 와 oldValue로 사용할 수 있다
- willSet과 didSet 둘 중 하나만 작성해도 된다!
var currentValue:Int = 100 {
willSet {
print("\(currentValue)에서 \(newValue)로 변경될 예정입니다")
}
didSet(oldData) {
print("\(oldData)가 \(currentValue)로 변경되었습니다")
}
}
- 변경하려는 값이 현재 값과 같아도 동작한다
- 함수, 메서드, 클로저, 타입 등의 지역/전역 변수에 모두 사용 가능
- 예시 1
struct Age {
var currentValue:Int = 100 {
willSet {
print("\(currentValue)에서 \(newValue)로 변경될 예정입니다")
}
didSet(oldData) {
print("\(oldData) 이/가 \(currentValue)로 변경되었습니다")
}
}
}
let me = Age()
// willSet 실행 -> 100에서 200로 변경될 예정입니다
me.currentValue = 200
// didSet 실행 -> 100 이/가 200로 변경되었습니다
- 예시 2
struct Money {
// 프로퍼티 감시자 사용
var currencyRate: Double = 1100 {
willSet(newRate) {
print("환율이 \(currencyRate)에서 \(newRate)으로 변경될 예정입니다")
}
didSet(oldRate) {
print("환율이 \(oldRate)에서 \(currencyRate)으로 변경되었습니다")
}
}
// 프로퍼티 감시자 사용
var dollar: Double = 0 {
// willSet의 암시적 매개변수 이름 newValue
willSet {
print("\(dollar)달러에서 \(newValue)달러로 변경될 예정입니다")
}
// didSet의 암시적 매개변수 이름 oldValue
didSet {
print("\(oldValue)달러에서 \(dollar)달러로 변경되었습니다")
}
}
// 연산 프로퍼티
var won: Double {
get {
return dollar * currencyRate
}
set {
dollar = newValue / currencyRate
}
/* 프로퍼티 감시자와 연산 프로퍼티 기능을 동시에 사용할 수 없습니다
willSet {
}
*/
}
}
var moneyInMyPocket: Money = Money()
// 환율이 1100.0에서 1150.0으로 변경될 예정입니다
moneyInMyPocket.currencyRate = 1150
// 환율이 1100.0에서 1150.0으로 변경되었습니다
// 0.0달러에서 10.0달러로 변경될 예정입니다
moneyInMyPocket.dollar = 10
// 0.0달러에서 10.0달러로 변경되었습니다
print(moneyInMyPocket.won)
// 11500.0
- 프로퍼티 감시자와 연산 프로퍼티를 함께 사용할 수 없다
'iOS > Swift' 카테고리의 다른 글
[Swift] 고차함수(1/3) map (0) | 2023.11.23 |
---|---|
[Swift] 상속 Inheritance (0) | 2023.11.21 |
[Swift] ARC/strong/weak/reference cycles(참조 순환) (1) | 2023.11.20 |
[Swift] 연산 프로퍼티 Computed Property (1) | 2023.11.20 |
[Swift] 클래스/구조체 언제 사용할까? (0) | 2023.11.20 |