Skip to content

Commit 3870645

Browse files
committed
warn on default access
1 parent 2364741 commit 3870645

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

Sources/ComposableArchitecture/SharedState/PersistenceKey/DefaultProvidingKey.swift

+25-7
Original file line numberDiff line numberDiff line change
@@ -12,22 +12,40 @@
1212
///
1313
/// - Parameter key: A string key identifying a value to share in memory.
1414
/// - 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
1620
where Self == DefaultProvidingKey<InMemoryKey<Value>> {
17-
DefaultProvidingKey(.init(key), defaultValue: defaultValue)
21+
DefaultProvidingKey(
22+
.init(key),
23+
defaultValue: defaultValue,
24+
warnOnDefaultValueAccess: warnOnDefaultValueAccess
25+
)
1826
}
1927
}
2028

2129
/// A decorator around an in-memory persistence strategy that provides a built-in default value.
2230
///
2331
/// 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 {
2634
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) {
2946
self.key = key
30-
self.defaultValue = defaultValue
47+
self._defaultValue = defaultValue
48+
self.warnOnDefaultValueAccess = warnOnDefaultValueAccess
3149
}
3250
public func load(initialValue: UnderlyingKey.Value?) -> UnderlyingKey.Value? {
3351
self.key.load(initialValue: initialValue)

0 commit comments

Comments
 (0)