Initialize state properties before first accessing

This commit is contained in:
david-swift 2024-09-03 07:19:04 +02:00
parent 34d43bc0a8
commit 65c06fae61
3 changed files with 27 additions and 14 deletions

View File

@ -36,24 +36,11 @@ public struct State<Value>: StateProtocol {
public var rawValue: Value {
get {
guard let value = content.value as? Value else {
let initialValue = getInitialValue()
let storage = StateContent.Storage(value: initialValue)
if var model = initialValue as? Model {
model.model = .init(storage: storage, force: forceUpdates)
model.setup()
content.storage = storage
content.value = model
} else {
content.storage = storage
}
return initialValue
return initialValue()
}
return value
}
nonmutating set {
if content.storage == nil {
_ = rawValue
}
content.value = newValue
}
}
@ -77,4 +64,25 @@ public struct State<Value>: StateProtocol {
self.forceUpdates = forceUpdates
}
/// Get the initial value.
/// - Returns: The initial value.
func initialValue() -> Value {
let initialValue = getInitialValue()
let storage = StateContent.Storage(value: initialValue)
if var model = initialValue as? Model {
model.model = .init(storage: storage, force: forceUpdates)
model.setup()
content.storage = storage
content.value = model
} else {
content.storage = storage
}
return initialValue
}
/// Set the storage up.
func setup() {
_ = initialValue()
}
}

View File

@ -12,5 +12,7 @@ protocol StateProtocol {
/// The state content.
var content: StateContent { get }
/// Set the storage up.
func setup()
}

View File

@ -69,6 +69,9 @@ struct StateWrapper: ConvenienceWidget {
let content = content().storage(data: data, type: type)
let storage = ViewStorage(content.pointer, content: [.mainContent: [content]])
storage.state = state
for element in state {
element.value.setup()
}
return storage
}