Monday, April 25, 2022

Heterogeneous Swift Dictionary With Strong Types

Ole Begemann:

The environment in SwiftUI is sort of like a global dictionary but with stronger types: each key (represented by a key path) can have its own specific value type. For example, the \.isEnabled key stores a boolean value, whereas the \.font key stores an Optional<Font>.

I wrote a custom dictionary type that can do the same thing. The HeterogeneousDictionary struct I show in this article stores mixed key-value pairs where each key defines the type of value it stores. The public API is fully type-safe, no casting required.

This is also similar to what the new AttributedString type uses. URLResourceValues takes a different approach, using a struct with optional properties.

1 Comment RSS · Twitter

Along those lines, I built a type safe rule system for SwiftUI a few years ago: http://www.alwaysrightinstitute.com/swiftuirules/#swiftui-rules

Maybe interesting, maybe not :-) Direct2SwiftUI builds on top of it.

Leave a Comment