Skip to content

Instantly share code, notes, and snippets.

@jhowlin
Created July 4, 2022 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhowlin/ffef2cc5553b8078b0a86a296f3d7bdb to your computer and use it in GitHub Desktop.
Save jhowlin/ffef2cc5553b8078b0a86a296f3d7bdb to your computer and use it in GitHub Desktop.
import Foundation
protocol StoreKey {
associatedtype Value
static func defaultValue() -> Value
}
struct MyKey: StoreKey {
typealias Value = Int
static func defaultValue() -> Int {
return 1
}
}
struct Store {
private var storage: [String: Any] = [:]
subscript<V: StoreKey>(member: V.Type) -> V.Value {
get {
let keyStr = String(describing: member)
return storage[keyStr] as? V.Value ?? V.defaultValue()
}
set {
let keyStr = String(describing: member)
storage[keyStr] = newValue
}
}
}
var store = Store()
let a = store[MyKey.self]
print(a)
// prints 1 (the default value)
store[MyKey.self] = 2
let b = store[MyKey.self]
print(b)
// prints 2 (the value we just set using subscript)
@jhowlin
Copy link
Author

jhowlin commented Jul 4, 2022

In SwiftUI, the environment allows setting and getting values where keys are types conforming to a protocol, and have default values. Here's a sketch of what the implementation might look like

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment