[SwiftUI] TCA Tutorial - Your first feature

별똥별·2024년 8월 30일

TCA

목록 보기
1/24

SwiftUI로 개발을 진행하면서 항상 MVVM 패턴을 적용하여 개발을 했다.
하지만,SwiftUI에서 MVVM은 호버보드로 날 수 있는데 굳이 바퀴를 달아서 달리는 것과 같은 말도 있었다.
Stop using MVVM for SwiftUI에 관한 글

그래서 다른 아키텍쳐를 찾아봤는데 TCA패턴이라는 것을 발견했다.
TCA 패턴 READM

관련 내용을 알아보니 기존의 MVVM은 양방향으로 간섭을 줄 수 있는데 TCA는 단방향으로 로직을 주고받기 때문에 훨씬 간결하고 클린하게 할 수 있다는 내용이었다.
그래서 관련 튜토리얼을 하나씩 따라하면서 파헤쳐보기로 했다.

The Composable Architecture Tutorials - TCA 튜토리얼

Your First Feature

Section 1. Create a reducer

import ComposableArchitecture


@Reducer
struct CounterFeature {
  @ObservableState
  struct State {
    var count = 0
  }
  
  enum Action {
    case decrementButtonTapped
    case incrementButtonTapped
  }
  
  var body: some ReducerOf<Self> {
    Reduce { state, action in
      switch action {
      case .decrementButtonTapped:
        state.count -= 1
        return .none
        
      case .incrementButtonTapped:
        state.count += 1
        return .none
      }
    }
  }
}

Section 2. SwiftUI와 통합

struct CounterView: View {
  let store: StoreOf<CounterFeature>
  
  var body: some View {
    VStack {
      Text("\(store.count)")
        .font(.largeTitle)
        .padding()
        .background(Color.black.opacity(0.1))
        .cornerRadius(10)
      HStack {
        Button("-") {
          store.send(.decrementButtonTapped)
        }
        .font(.largeTitle)
        .padding()
        .background(Color.black.opacity(0.1))
        .cornerRadius(10)
        
        Button("+") {
          store.send(.incrementButtonTapped)
        }
        .font(.largeTitle)
        .padding()
        .background(Color.black.opacity(0.1))
        .cornerRadius(10)
      }
    }
  }
}

Section 3. 앱에 통합하기

import ComposableArchitecture
import SwiftUI


@main
struct MyApp: App {
  static let store = Store(initialState: CounterFeature.State()) {
    CounterFeature()
      ._printChanges()
  }
  
  var body: some Scene {
    WindowGroup {
      CounterView(store: MyApp.store)
    }
  }
}
profile
밍밍

0개의 댓글