DEV Community

Cover image for SwiftUI @Environment and BindableObject
✨ thetealpickle πŸ“±
✨ thetealpickle πŸ“±

Posted on

SwiftUI @Environment and BindableObject

The drop of SwiftUI this summer 2019 shook the iOS/Swift dev game. The way views are created and how data flows through apps have become declarative. BindableObject, Environment, State, Binding are new tools to cut through the waves and make it to the other side.


Property Wrapper & Protocols

New in Swift 5.1, property wrappers. Property wrappers wrap property access with additional behavior. @Environment is a property wrapper.

Protocols define a set of requirements which are then implemented by the adopting class, structure, or enumeration. BindableObject is a protocol.

Environment

The Environment property wrapper is part of the new Combine framework and is designed as a general purpose container for all types of data. The Environment data is used for indirect data passing and pushes dependencies down the hierarchy. Environment data has read-only access.

Writing data into the environment is done by using the .environmentObject modifier on the object you would like to go into the environment.

Environment vs Binding

Binding is another data flow tool for SwiftUI views, more information can be found here.

Environment and Binding are two different tools with the same core functionality, passing dependencies through the view hierarchy. If your entire app is a read-only app, the app could be built using entirely one OR the other. The question, how would you like to access your data?

Environment can be leveraged as a work around from passing a model at every view transition point. Environment is like bag full of candy being passed around the group. Whereas with Binding, everyone holds and passes around each individual candy.

Another note, Binding provides read/write access. Environment is read-only. For data which child views need to be able to update, the Binding wrapper should be used instead.

BindableObject

The BindableObject protocol is part of the new Combine framework and is designed to provide an external reference to your custom model and have SwiftUI track attribute changes over time using publishers.

Combine uses a Publisher, Operator, Subscriber model flow. By conforming your custom model to the BindableObject protocol, the model becomes setup to trigger view changes to all subscribers in the view hierarchy.

BindableObject is a way to bring SwiftUI’s declarative data handling to custom models. BindableObject brings us into the beginning dive into the new Combine framework. A new age.

@thetealpickle on the internet. Namaste.

This article was brought to you by JESSICA JEAN JOSEPH Β© THETEALPICKLE

Top comments (0)