Why the boilerplate code to create a custom Environment value?

Hi, this is a question for SwiftUI developers. Below is an example code to create a custom Environment value:

struct SomeThingKey: EnvironmentKey {
  static var defaultValue: Int = 0

extension EnvironmentValues {
  var someThing: Int {
    get { self[SomeThingKey.self] }
    set { self[SomeThingKey.self] = newValue }

In my opion, the code in the extension is mostly boilerplate. The only useful information is the property name for the custom value. If so, why not put the name in EnvironmentKey protocol? That would be much more elegant, I think.

Of course, I'm assuming that it's possible to create a property at runtime, which I don't know for sure. But from my understanding, the implementation of Environment has already used some dynamic features, like getting all types that conform to EnvironmentKey and create instances, etc., I suppose it could get further to remove the boilerplate code. Just my thought.

On a second thought, given that Swift is a type-safe language, it seems impossible to add a new property at runtime. However, since user accesses environment value through property wrapper, the EnvironmentValues.<propertyname> is an internal API. Its main benefit seems to enforce keyname type safety through keypath. I wonder if there are other ways (like enum or something) that allows SwiftUI to enforce keyname type safety but doesn't require user creating a property manually? Just my random thoughts.

If you want to provide a suggestion to the SwiftUI developers, you should probably send an enhancement request to Apple via Feedback Assistant. SwiftUI is not part of the Swift ecosystem, but, is a private Apple-only framework. It's not known how many SwiftUI developers frequent this site, however, they all get feedback requests.

Sorry, I didn't realize that (though it's quite obvious once you pointed it out). I've submitted a suggestion via Feedback Assistant. First time using it :)

Terms of Service

Privacy Policy

Cookie Policy