1

From my understanding @Environment is specifically there to work with SwiftUI’s own pre-defined keys and @Environment is great for reading out things like device is in dark mode or light mode, what size class your view is being rendered with, and more – fixed properties that come from the system.

  • Why we need to create custom environment values with key path system
  • Under the hood some modifiers like alignment changes environment value. Why it is required to modify environment value instead of wrapper View
  • If we can set by modifier why we need to inject with .environment modifier
  • Why can't we use Singleton or Global instead of environment value
salman siddiqui
  • 882
  • 1
  • 10
  • 28

1 Answers1

0

Why we need to create custom environment values with key path system

Probably for convenience, alternatives are strings (not safe and not convenient) and types (would not allow for more than 1 instance of a type).

Under the hood some modifiers like alignment changes environment value. Why it is required to modify environment value instead of wrapper View

Because you need to somehow tell the views down the hierarchy how to behave. You don't know what these views will be.

If we can set by modifier why we need to inject with .environment modifier

It's the same thing, convenience. .environment and some .myCustomEnvironmentValue would be equivalent.

Why can't we use Singleton or different type instead of environment value

Singleton is single, where environments are scoped to hierarchy. You can have different values of the same environment in different parts of the app.

eXCore
  • 296
  • 2
  • 8