Skip to content

[Swift] 속성 감시자 #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
seungchan2 opened this issue May 17, 2022 · 0 comments
Closed

[Swift] 속성 감시자 #45

seungchan2 opened this issue May 17, 2022 · 0 comments
Assignees
Labels

Comments

@seungchan2
Copy link
Owner

seungchan2 commented May 17, 2022

속성 감시자 willSet didSet

  • 저장속성 자체는 var로만 선언 가능 (let은 상수이므로 값이 변하질 않아 선언 불가)

  • 자료형을 선언하는 것은 일반 변수와 동일(기본값을 넣으면 형식 추론 방식 가능)

  • 저장 속성의 변화시점을 관찰하는 실질적 메서드(타입/인스턴스 둘다 가능은 함)


  • willSet 또는 didSet 중에서 한가지만 구현 하면됨(일반적으로 didSet으로 구현)

 var nameList: [String] = [] {
        didSet {
            peopleNamePickerView.reloadAllComponents()
        }
    }
  • 변수가 변할 때 업데이트 하려는 패턴 구현할때 사용 

    예시) 상태메세지, 프로필 사진 서버에서 변화 ➡ (바로) 화면 업데이트
 


  • 속성감시자 추가 가능한 경우(인스턴스 속성)


  1. 저장 속성(상속한 저장속성은 재정의 불가, 감시자 추가는 가능)


  2. 상속한 계산 속성을 재정의해 속성관찰자 추가 가능

struct Person {
    var age: Int {
        willSet {
            // some code
        }
        didSet {
            // some code
        }
    }
}

willSet
값이 변할 때 새 값이 저장되기 직전에 호출

didSet
값이 변할 때 새 값이 저장된 직 후에 호출

@seungchan2 seungchan2 self-assigned this May 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant