속성 감시자(Property Observers)는 Swift에서 특정 속성의 값이 변경되기 직전 또는 변경된 직후에 실행할 코드를 정의할 수 있는 기능입니다. 이를 통해 속성의 상태 변화를 감지하고, 추가 작업을 수행하거나, 부수효과(side effects)를 관리할 수 있습니다.
willSet
과 didSet
두 가지 속성 감시자를 제공합니다var count: Int = 0 {
willSet {
print("count가 \(count)에서 \(newValue)로 변경될 예정입니다.")
}
didSet {
print("count가 \(oldValue)에서 \(count)로 변경되었습니다.")
}
}
count = 10
// 출력:
// count가 0에서 10로 변경될 예정입니다.
// count가 0에서 10로 변경되었습니다.
// UI 업데이트 메서드
private func updateUI() {
countLabel.text = "\(count)"
}
// 버튼 액션
@objc private func incrementCount() {
count += 1
updateUI() // 값 변경 후 수동으로 UI 업데이트
}
이런 코드를 아래처럼 활용 가능
var count: Int = 0 {
didSet {
countLabel.text = "\(count)"
}
}
var temperature: Int = 20 {
didSet {
if temperature < 0 || temperature > 100 {
print("온도가 유효하지 않습니다. 값을 복원합니다.")
temperature = oldValue
}
}
}
var username: String = "" {
willSet {
print("username이 '\(username)'에서 '\(newValue)'로 변경될 예정입니다.")
}
didSet {
print("username이 '\(oldValue)'에서 '\(username)'로 변경되었습니다.")
}
}
var count: Int = 0 {
didSet {
print("count 변경됨")
}
}
let counter = Counter() // 초기화 시 호출되지 않음
var computedProperty: Int {
get {
// 값 반환
}
set {
// 값 설정
}
}
var count: Int = 0 {
didSet {
count += 1 // 위험: 무한 루프 발생 가능
}
}