SwiftUIの基本を身につけたい方はこちら

【SwiftUI】TCAのサンプルコード

こちらの公式のやつを無駄なとこを省いただけです。

参考 pointfreeco/swift-composable-architectureGitHub

コード

import SwiftUI
import ComposableArchitecture

@main
struct SampleProjectApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView(
                store: Store(
                    initialState: CounterState(),
                    reducer: counterReducer,
                    environment: CounterEnvironment()
                )
            )
        }
    }
}
import SwiftUI
import ComposableArchitecture

struct ContentView: View {
    let store: Store<CounterState, CounterAction>
    
    var body: some View {
        CounterView(store: self.store)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(
            store: Store(
                initialState: CounterState(),
                reducer: counterReducer,
                environment: CounterEnvironment()
            )
        )
    }
}
import SwiftUI
import ComposableArchitecture

struct CounterView: View {
    let store: Store<CounterState, CounterAction>
    
    var body: some View {
        WithViewStore(self.store) { viewStore in
            HStack {
                Button("−") {
                    viewStore.send(.decrementButtonTapped)
                }
                Text("\(viewStore.count)")
                Button("+") {
                    viewStore.send(.incrementButtonTapped)
                }
            }
        }
    }
}
import SwiftUI
import ComposableArchitecture

struct CounterState: Equatable {
    var count = 0
}

enum CounterAction: Equatable {
    case decrementButtonTapped
    case incrementButtonTapped
}

struct CounterEnvironment { }

let counterReducer = AnyReducer<CounterState, CounterAction, CounterEnvironment> { state, action, _ in
    switch action {
    case .decrementButtonTapped:
        state.count -= 1
        return .none
    case .incrementButtonTapped:
        state.count += 1
        return .none
    }
}

評価