|
12 | 12 | ///
|
13 | 13 | /// - Parameter key: A string key identifying a value to share in memory.
|
14 | 14 | /// - Returns: An in-memory persistence key.
|
15 |
| - public static func inMemory<Value>(_ key: String, defaultValue: Value) -> Self |
| 15 | + public static func inMemory<Value>( |
| 16 | + _ key: String, |
| 17 | + defaultValue: Value, |
| 18 | + warnOnDefaultValueAccess: Bool = false |
| 19 | + ) -> Self |
16 | 20 | where Self == DefaultProvidingKey<InMemoryKey<Value>> {
|
17 |
| - DefaultProvidingKey(.init(key), defaultValue: defaultValue) |
| 21 | + DefaultProvidingKey( |
| 22 | + .init(key), |
| 23 | + defaultValue: defaultValue, |
| 24 | + warnOnDefaultValueAccess: warnOnDefaultValueAccess |
| 25 | + ) |
18 | 26 | }
|
19 | 27 | }
|
20 | 28 |
|
21 | 29 | /// A decorator around an in-memory persistence strategy that provides a built-in default value.
|
22 | 30 | ///
|
23 | 31 | /// See ``PersistenceKey/inMemory(_:)`` to create values of this type.
|
24 |
| -public struct DefaultProvidingKey<UnderlyingKey: PersistenceKey>: Hashable, PersistenceKey, Sendable |
25 |
| - where UnderlyingKey: Hashable & Sendable, UnderlyingKey.Value: Hashable & Sendable { |
| 32 | + public struct DefaultProvidingKey<UnderlyingKey: PersistenceKey>: Hashable, PersistenceKey, Sendable |
| 33 | + where UnderlyingKey: Hashable & Sendable, UnderlyingKey.Value: Hashable & Sendable { |
26 | 34 | let key: UnderlyingKey
|
27 |
| - let defaultValue: UnderlyingKey.Value |
28 |
| - init(_ key: UnderlyingKey, defaultValue: UnderlyingKey.Value) { |
| 35 | + let _defaultValue: UnderlyingKey.Value |
| 36 | + let warnOnDefaultValueAccess: Bool |
| 37 | + var defaultValue: UnderlyingKey.Value { |
| 38 | + get { |
| 39 | + if warnOnDefaultValueAccess { |
| 40 | + runtimeWarn("Accessed default value for shared state using key: \(key)") |
| 41 | + } |
| 42 | + return _defaultValue |
| 43 | + } |
| 44 | + } |
| 45 | + init(_ key: UnderlyingKey, defaultValue: UnderlyingKey.Value, warnOnDefaultValueAccess: Bool) { |
29 | 46 | self.key = key
|
30 |
| - self.defaultValue = defaultValue |
| 47 | + self._defaultValue = defaultValue |
| 48 | + self.warnOnDefaultValueAccess = warnOnDefaultValueAccess |
31 | 49 | }
|
32 | 50 | public func load(initialValue: UnderlyingKey.Value?) -> UnderlyingKey.Value? {
|
33 | 51 | self.key.load(initialValue: initialValue)
|
|
0 commit comments