0
2

More than 1 year has passed since last update.

【SwiftUI】TCAでアラートを実装する

Posted at

はじめに

最近、個人開発アプリをTCAにリアーキテクチャしています。
これから学習も兼ねて、基本的な形を記事にしていこうと思います。

実装

ContentView
import SwiftUI
import ComposableArchitecture

struct ContentView: View {
    let store: StoreOf<Feature>

    var body: some View {
        WithViewStore(store) { viewStore in
            Button {
                viewStore.send(.alertPresented)
            } label: {
                Text("アラート")
            }
            .alert(store.scope(state: \.alert), dismiss: .alertDismissed)
        }
    }
}
Feature
import Foundation
import ComposableArchitecture

struct Feature: ReducerProtocol {
    struct State: Equatable {
        var alert: AlertState<Feature.Action>?
    }

    enum Action: Equatable {
        case alertPresented
        case alertDismissed
    }

    func reduce(into state: inout State, action: Action) -> EffectPublisher<Action, Never> {
        switch action {
        case .alertPresented:
            state.alert = .init(title: .init("テストアラート"))
            return .none
        case .alertDismissed:
            state.alert = nil
            return .none
        }
    }
}

完成

Simulator Screen Recording - iPhone 14 Pro - 2023-04-06 at 20.32.28.gif

おわり

TCAめっちゃ気に入りました笑

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2