Source of Truth란???

SwiftUI에서의 Source of Truth란 데이터의 일관성과 정확성을 유지하는 중요한 개념을 의미한다.

SwiftUI앱 내에서 사용자 인터페이스(UI)는 데이터 모델에 바인딩 되어있다.

이말은 기존의 UIKit과 다르게 SwiftUI는 데이터모델인 @State에 UI가 바인딩되어 있기 때문에 UI는 데이터 모델의 변경에 의해서 자동으로 반응하고, 변경된다.

하지만 이렇게 UI를 변경하는 상태가 여러곳에서 복사되고 변경되고 사용되어 진다면, 이는 사용자 경험(UX)의 일관성이나 정확성 유지에 굉장히 취약해 진다. (사이드 이팩트가 발생함)

따라서 SwiftUI에서는 SwiftUI에서는 보통 @State, @Binding, @ObservedObject, @EnvironmentObject 등의 속성 래퍼를 사용하여 데이터 모델을 관리한다.

이해하기 위한 간단한 예시 코드

예시코드

struct ContentView: View {
    
	  @State private var isDestinationPresented = false
    
    
    var body: some View {
        Text("hi").onTapGesture {
            self.isDestinationPresented.toggle()
        }.sheet(isPresented: $isDestinationPresented) {
            DestinationView(isDestinationPresented: self.$isDestinationPresented)
        }
    }
}
 
struct DestinationView: View {
    @Binding var isDestinationPresented: Bool
    var body: some View {
        NavigationView {
            NavigationLink(destination: AnotherDestinationView(isDestinationPresented: $isDestinationPresented)) {
                Text("where to go")
            }
        }
    }
}

struct AnotherDestinationView: View {
    @Binding var isDestinationPresented: Bool
    var body: some View {
        NavigationView {
            Text("dismiss all").onLongPressGesture {
                self.isDestinationPresented = false
            }
        }
    }
}

코드 설명

ContentView, DestinationView, anotherDestinationView

총 3개의 뷰에서 해당 버튼을 누르면, 서로의 뷰를 호출하도록 설정해두었다.

여기에서 @State를 통해서 하나의 single source of truth가 생성된다.

isDestinationPresented라는 상태를 통해서 처음 content뷰에서 버튼을 눌렀을때, 해당 상태가 toggle로 true가 되고, 이를 통해 DestinationView가 떠오른다.