A colossal Dreamer: GR鐵塔-天生我材

SwiftUI - ContainerView ⨁ ContentView 본문

Development/아이폰

SwiftUI - ContainerView ⨁ ContentView

江多林 2022. 9. 13. 10:00

ContainerView(@state) ⨁ ContentView(@view)

 

로직과 상태와 View구성의 3대 SwiftUI 구성요소는

서로 성격이 다르지만,

하나의 ContentView 에 모두 우겨넣는 상황에 빠지면,

굉장히 뚠뚠한 ContentView 를 만나게 된다.

뚠뚠한 친구들의 특징은 재사용이 거의 불가능하다는 것.

 

재사용가능하게 구성하는 하나의 팁

 

ContainerView 에서만 @State, @ObservedObject 를 가지도록 제한하고,

ContentView 에서는 @Bind 만 가지도록 강제하는 것.

 

이렇게 구성하면, ContentView 는 ViewModel 과의 interaction 이

VM→V 단방향으로만 이뤄지게 되고,

V→VM 동작은 @Binding 을 경유해 ContainerView 를 통해서 이뤄지게 된다.

이것은 모든 V→VM 이벤트가 ContainerView 를 거쳐가게 되어

 

로직을 파악할 때 ContainerView 를 읽는 것으로만 파악할 수 있게되며,

ContentView 는 생성시에 지정된 Bind, Property 에 따른 단방향함수로 인식할 수 있게된다.

 

다시 말해서,

ContainerView 는 로직을 읽고, 검증하는 진입점으로써 역할하게 되고,

ContentView 는 입력(Binding, Property)에 따는 단순 view 역할하게 되며,

이것은 test 가능한 코드가 되는 것이다.

 

참조: https://swiftwithmajid.com/2022/03/16/functional-core-imperative-shell-in-swift-unidirectional-flow/

 

Functional core Imperative shell in Swift. Unidirectional Flow.

A few weeks ago, we talked about the idea of Functional core and Imperative shell in Swift. The goal is to extract the pure logic using value types and keep side effects in the thin object layer. This week, we will look at how we can apply this approach in

swiftwithmajid.com