DEV Community

Cover image for Redux-like state container in SwiftUI. Basics.
Sergey Leschev
Sergey Leschev

Posted on • Edited on

Redux-like state container in SwiftUI. Basics.

The main idea here is describing the whole app state by using a single struct or composition of structs. Assume that we are working on a Github repos search app where the state is the repos array that we fetch matching some query using Github API.

struct AppState {
    var searchResult: [Repo] = []
}
Enter fullscreen mode Exit fullscreen mode

Next step is passing the read-only app state to every view inside the app. The best way for doing that is SwiftUI’s Environment feature. We can put an object holding the whole app state in the Environment of the root view. Root view will share its Environment with all child views.

final class Store: ObservableObject {
    @Published private(set) var state: AppState
}
Enter fullscreen mode Exit fullscreen mode

We create a store object that stores the app state and provides read-only access to it. State property uses @Published property wrapper that notifies SwiftUI during any changes. It allows us to keep up to date the whole app by deriving it from a single source of truth.



Contacts
I have a clear focus on time-to-market and don't prioritize technical debt. And I took part in the Pre-Sale/RFX activity as a System Architect, assessment efforts for Mobile (iOS-Swift, Android-Kotlin), Frontend (React-TypeScript) and Backend (NodeJS-.NET-PHP-Kafka-SQL-NoSQL). And I also formed the work of Pre-Sale as a CTO from Opportunity to Proposal via knowledge transfer to Successful Delivery.

🛩️ #startups #management #cto #swift #typescript #database
📧 Email: sergey.leschev@gmail.com
👋 LinkedIn: https://linkedin.com/in/sergeyleschev/
👋 LeetCode: https://leetcode.com/sergeyleschev/
👋 Twitter: https://twitter.com/sergeyleschev
👋 Github: https://github.com/sergeyleschev
🌎 Website: https://sergeyleschev.github.io
🌎 Reddit: https://reddit.com/user/sergeyleschev
🌎 Quora: https://quora.com/sergey-leschev
🌎 Medium: https://medium.com/@sergeyleschev

Top comments (0)