Created
July 4, 2022 13:32
-
-
Save jhowlin/ffef2cc5553b8078b0a86a296f3d7bdb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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