Sobes.tech
Junior — Senior

Moving screen state to an external object

livecode

Task condition

Move the state management of the main screen from the view to an external object — for example, to a ViewModel or Service. Such an object will act as the single source of truth and can be passed down through the component hierarchy.

enum HomeState {
    case loading
    case loaded(Int)
    case error(String)
}

struct HomeView: some View {
    @State private var homeState: HomeState = .loading

    var body: some View {
        ZStack {
            switch homeState {
            case .loading:
                ProgressView()
            case .loaded(let number):
                Text("Number is: \(number)")
            case .error(let error):
                Text("Oops! \(error)")
            }
        }
    }
}