How to handle different states in a screen in iOS

Issue #469

If there are lots of logics and states inside a screen, it is best to introduce parent and child container, and switch child depends on state. Each child acts as a State handler.

In less logic case, we can introduce a Scenario class that holds the state. So the ViewController can be very slim. The thing with State is that all possible scenarios are clear and required to be handled

final class UserDetailScenario {
    enum State {
        case unknown
        case getUser(Email)
        case newUser(Email)
        case existingUser(User)
        case failure(Error)
    }
    
    var state: State = .unknown(nil) {
        didSet {
            self.reload()
        }
    }
    
    private func reload() {
        switch state {
        case .unknown:
            handleUnknown()
        case .getUser(let email):
            handleGetUser(email: email)
        case .newUser(let email):
            handleNewUser(email: email)
        case .existingUser(let user):
            handleExistingUser(user: user
        case .failure(let error):
            logError(error)
        }
}
Written by

I’m open source contributor, writer, speaker and product maker.

Start the conversation