💻
@State, @Binding (프로퍼티 래퍼 - 2 )
joho2022
2025. 12. 24. 00:19

@State
뷰가 소유하는 값(Source of Truth) 을 저장하고, 그 값이 바뀌면 해당 뷰의 body를 다시 계산한다.
문서에 따르면,
SwiftUI가 제공하는 저장소 관리 방식과 충돌할 수 있으므로,
멤버와이즈 이니셜라이저에서 state를 설정하지 못하도록 state를 private으로 선언하기를 권장한다.
뷰와 그 하위 뷰에만 국한된 로컬 상태를 저장할 때 사용한다.
항상 기본값으로 초기화되어야 하며, 선언 시점에 값이 필요하다.
struct EditorView: View {
@State private var text: String
init(initialText: String) {
self._text = State(initialValue: initialText)
}
var body: some View {
TextField("edit", text: $text)
}
}
물론 화면 진입 시점의 초기값처럼 외부 데이터로 상태를 시작해야 하는 경우에는,
@State를 직접 주입하기보다는 State(initialValue:)를 통해 초기화 시점에만 값을 반영하고
이후에는 뷰의 로컬 상태로 관리하는 방식을 사용한다.
@Binding
뷰가 소유하지 않은 상태를 읽고, 수정까지 할 수 있도록 연결해주는 프로퍼티 래퍼
struct ParentView: View {
@State private var isPlaying = false
var body: some View {
PlayerToggle(isPlaying: $isPlaying)
}
}
struct PlayerToggle: View {
@Binding var isPlaying: Bool
var body: some View {
Toggle("Play", isOn: $isPlaying)
}
}
- @State → 상태의 소유자 (Source of Truth)
- @Binding → 그 상태를 수정할 수 있는 연결
PlayerToggle는 isPlaying을 소유하지 않지만,
변경은 가능하고, 변경 결과는 자동으로 상위 View에 반영된다.
Reference
State | Apple Developer Documentation
A property wrapper type that can read and write a value managed by SwiftUI.
developer.apple.com
Binding | Apple Developer Documentation
A property wrapper type that can read and write a value owned by a source of truth.
developer.apple.com