What's the difference between @Environment and @EnvironmentObject in SwiftUI?
From what I found from the documents, @Environment seems to be meant to be used for global dependencies like ColorScheme. But I couldn't find any precise difference between them. For example, can they be used interchangeably?
Here is the notes I have prepared for myself. Could be useful,
@EnvironmentObject
@ObservedObject
@Published
to notify changes to view which actively using the object@EnvironmentObject
rather than @ObservedObject
. Set data to be passed in V1 and retrieve it in V5(or wherever needed). Code will be much simple.@Environment
Thanks!👨🏻💻
I want to add something to others' answer.
@Environment
is value type but @EnvironmentObject
is reference type.
You can only use a single instance of objects in @EnvironmentObject
.If you add another instance of an object, it will replace the previous one.
But as, @Environment
key value pair, just make sure key is different.
You just need to use @EnvironmentObject var object: Object
to make an object retrieve the instance from the environment, and inject the instance by .environmentObject(Object())
On the other hand, there are many predefined @Environment
system-managed environment values. You can also create custom one. It needs to be struct
type and conforms to EnvironmentKey
.
Here is an example,
struct SunlightKey: EnvironmentKey {
static var defaultValue: Double = 1.09
}
Then add it to the EnvironmentValues
as an extension of it.
Here is a basic example
extension EnvironmentValues {
var sunlight: Double {
get { self[SunlightKey.self] }
set { self[SunlightKey.self] = newValue }
}
}
Then, use it like, @Environment(\.sunlight) var sunlight
in view file and inject value by .environment(\.sunlight, 4.05)
Hope, this helps
@Enviroment gives you access to values of properties such as user settings (e.g colour scheme, layout direction etc.) or properties of the view such as EditMode or PresentationMode. @EnviromentObject is defined by you and available to all views and changes to it drive updates to your views.
Both of them @Environment
and @EnvironmentObject
are property wrappers while @Environment
keeps values with predefined keys, @EnvironmentObject
keeps not only predefined keys but also arbitrary values. For example if you need to keep information about your User object which includes name, age, gender etc. you need to use @EnvironmentObject
, whereas if you would like to keep whether device is in dark or light mode, system local language, calendar preferences, edit mode it is great for using @Environment
.
@Environment(\.locale) var locale: Locale
@EnvironmentObject var user: User // is an object where you keep user-related information
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With