Skip to content

The Elm Architecture sample v2 implemented with Swift

License

Notifications You must be signed in to change notification settings

yoching/SwiftElmSample2

Repository files navigation

The Elm Architecture sample v2 implemented with Swift

This includes Command and Subscription which are excluded for simplicity in v1.

Differences from v1

  • elements
    • add Command
    • add Subscription
  • behavior
    • save current value in UserDefaults using Command
    • load value from UserDefaults using Command
    • observe app state change (entered background/foreground) using Subscription, then save/load value

Command is a way to declare side-effects (networking, storage, ...), and Subscription is a way to subscribe outer changes (like notifications).
Please read here for the details.

AppState

struct AppState {

    // MODEL
    var value: Int

    // UPDATE
    enum Message {
        case increment
        case decrement
        case save
        case load
        case loaded(Int)
    }

    mutating func update(_ message: Message) -> [Command<Message>] {
        switch message {
        case .increment:
            value = value + 1
            return []
        case .decrement:
            value = value - 1
            return []
        case .save:
            return [.save(value: value)]
        case .load:
            return [.load(available: { .loaded($0) })]
        case .loaded(let value):
            self.value = value
            return []
        }
    }

    // SUBSCRIPTIONS
    var subscriptions: [Subscription<Message>] {
        return [
            .notification(
                name: UIApplication.didBecomeActiveNotification,
                { notification -> Message in
                    return .load
            }),
            .notification(
                name: UIApplication.willResignActiveNotification,
                { notification -> Message in
                    return .save
            })
        ]
    }

    // VIEW
    var viewController: ViewController<Message> {
        return ._viewController(
            .stackView(
                views: [
                    .button(text: "-", onTap: .decrement),
                    .label(text: "\(value)"),
                    .button(text: "+", onTap: .increment),
                    .button(text: "save", onTap: .save),
                    .button(text: "load", onTap: .load)
                ],
                axis: .vertical,
                distribution: .fillEqually
            )
        )
    }
}

References

About

The Elm Architecture sample v2 implemented with Swift

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages