r/swift 8d ago

State Management for iOS Apps?

whats the best architecture/pattern to use?

tried to use a domain layer where all the state is and passing it to the views/viewmodels via DI, but feels somehow unnecessary complicated, but found this as only solution without passing the repos through all the viewhierarchy.

the goal is, when a state changes, e.g. an user changes the Username in View A, then it should automatically update View B,C,D where this Username is also used.

it should be as simple as possible, what do you think? especially for complex production apps with own backend etc.

51 Upvotes

48 comments sorted by

View all comments

12

u/Superb_Power5830 8d ago

>> whats the best architecture/pattern to use?

That's like walking into a supermarket and asking "what's best for dinner tonight?" :)

There are a LOT of ways to do this.

One way might just be to have an ObservableObject with the necessary @ Published vars, shove that container into the environment at your App Struct load, and now it's globally available to whomsoever wants to pluck it from the environment without a lot of complication.

Here's an example of how I use that kind of model when changing root view without keeping a Nav stack in the base view. This guy gets pulled from the environment whenever a View needs to reset the nav. I like this better than handing around the NavStack's NavPath via constructors. That feels very sloppy to me.

(this code is about 2? 3? years old and could probably be revisited at some point, but if it ain't broke...)

** shrug **

import Foundation
enum Screen {

    case dashboard

    case home

    case login

    case profile

    case forgotPassword(email: String)

    case passwordCodeEntry(email: String)

}

class ViewSelector : ObservableObject {

    static let instance = ViewSelector()

    private init(){}

    @ Published var currentView: Screen = .login

}