Skip to content

iShawnWang/StateMachine

Repository files navigation

StateMachine

Swift Version Build Status License codebeat-badge

A simple State Machine to organize your ViewController

Why use StateMachine

This demonstrate the cycle of a basic ViewController

I want to show different view to notify user the current state of the App

  • refreshing : show ActityIndocator
  • error : show error image and a retry button
  • list: show the data that retrived from the network

And this works perfect with FSM (Finite-state machine)

Usage

There 2 main class, ViewStateMachine and StateMachine

  1. StateMachine is a generic FSM
  2. ViewStateMachine is build on StateMachine for switching views when enter different state

Check demo code for example

ViewStateMachine

Check ViewStateMachineDemo.swift for example

1. In your ViewController create ViewStateMachine and DefaultViewStateMachineDelegate

DefaultViewStateMachineDelegate demonstrate switch view when state changed

    let uiStateDelegate = DefaultViewStateMachineDelegate()
    lazy var uiState:ViewStateMachine<DefaultViewStateMachineDelegate> = {
        let m = ViewStateMachine(superView: self.view, delegate: self.uiStateDelegate)
        return m
    }()
2. Change State with view
    let failedView = StateView.loadFromXib()
    failedView.label.text = "failed"
    self.uiState.enter(state:ViewState(failed:failedView))

StateMachine

Check StateMachineDemo.swift for example

0. Create you state
    enum DemoState {
        case error
        case success
    }
1. Create a StateMachine instance
    class StateMachineDemo: UIViewController {
    
        lazy var stateMachine:StateMachine<StateMachineDemo> = {
            let sm = StateMachine(delegate: self)
            return sm
        }()
    }
2. Implement StateMachineDelegate
    extension StateMachineDemo: StateMachineDelegate {
        typealias State = DemoState
        
        func canEnter(state: DemoState) -> Bool {
            return true
        }
        
        func transit(from: DemoState?, to: DemoState) {
            switch to {
            case .error:
                print("error")
            case .success:
                print("success")
            }
        }
    }
3. Change the state
    self.stateMachine.enter(state: .success)

Thanks

This project is for studying, you'd prefer using libs below :

aschuch/StatefulViewController narfdotpl/SwiftyStateMachine

Contact

It seems that my README is a bit longer than the code i write :D

License

Distributed under the GPL v3 license. See LICENSE for more information.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages