Current situation
Shared state extension supports a simple dictionary driven store to save every single state and allows scenes to manipulate the state through the capabilities provided by shared state extension.
Developer needs to define a set of keys in any type which conform to Hashable
protocol, then use traditional key-value way to get or put state onto the store, but literal keys might cause bugs due to typos, based on that, we decided to introduce key path into shared state extension.
How we work on shared state extension with key path
Key path is a feature provided by Swift, which give us a safer way to work on variables because of static type.
To improve the experience about using shared state extension, this time we introduced key path to this extension to free developers from typo caused bugs.
There are two types to make it runs, one is SharedStateKey
, another one is SharedStateValues
.
SharedStateKey
represents a type for you to define your custom keys, here is a case:
struct TimestampKey: SharedStateKey {
// this will give compiler a hint about concrete type.
static var currentValue: TimeInterval?
}
SharedStateValues
is a struct acts as entry point for you to extend variables as many as you like, which will also generate key path for your custom values, below is a case:
extension SharedStateValues {
// this will generate a key path for `timestamp` variable.
var timestamp: TimeInterval? {
get { Self[TimestampKey.self] }
set { Self[TimestampKey.self] = newValue }
}
}
Above are all you need to do before making your variables can be shared between different scenes.
After that, you can get or put your variables by as same as before, the only one difference is you pass key path to method as arguments.
scene.sbx.getSharedState(by: \.timestamp)
// or
scene.sbx.putSharedState(by: \.timestamp, sharedState: value)
We also know the power of property wrapper, especially we have seen tons of usage of them in SwiftUI, so here we bring a new property wrapper for key path driven shared state extension, just like how @Environment
works in SwiftUI.
class ViewController: UIViewController, Scene {
// ...
@SharedStateInjected(\.timestamp)
var timestamp: TimeInterval?
}
Hope this newer, safer way to share state between scenes can reduce risks and improve experience to a higher level.
Implemented in #11