Custom Environment Variable in your ‘SwiftUI’ Project. How to define Environment Variable like a senior developer.

There are common problems encountered while developing with SwiftUI. How do I manage global state or global variable. How do I inject those variables? What if there are a lot of nested views? If you don’t think about this, your code can get messy.

There are many ways to fix this issue.

  • Environment Variable

Here, I introduce you the easiest solution. Let’s learn about Creating Your Custom Environment Variable

Prepare Your Project

parent view and its child view

We now have only one ParentView and one ChildView which has Rectangle. Now I’m going to define Rectangle Size with environment variable.

Define EnvironmentKey and Environment Values

EnvironmentKey and EnvironmentValues

Define your environment key-values. Key conforms to EnvironmentKey and must have variable called defaultValue. Its datatype is generic. It means you can put any data type you want.

You can define your EnvironmentValues through extension. This is where we define variable name and its values. For example, here we can access rectangleSize with @Environemnt(\.rectangleSize). It’s computed property. You can give more logics when get or set is called.

Access your defined environment variable

How to use your custom environment variable

Now you can set new values with .environment(\.rectangleSize, 150) in ParentView and ChildView can access rectangleSize.

Entire Code

Conclusion

Sooner or later, you will face a problem with multiple nested views. Your view properties might explode. Believe me, every declarative framework has these problems. But if you have well-defined environment variables, your code will be more efficient and readable.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!