Skip to content
This repository has been archived by the owner on Oct 17, 2024. It is now read-only.

Commit

Permalink
Initialize state properties before first accessing
Browse files Browse the repository at this point in the history
  • Loading branch information
david-swift committed Sep 3, 2024
1 parent 34d43bc commit 65c06fa
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 14 deletions.
36 changes: 22 additions & 14 deletions Sources/Model/Data Flow/State.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand All @@ -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()
}

}
2 changes: 2 additions & 0 deletions Sources/Model/Data Flow/StateProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,7 @@ protocol StateProtocol {

/// The state content.
var content: StateContent { get }
/// Set the storage up.
func setup()

}
3 changes: 3 additions & 0 deletions Sources/View/StateWrapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down

0 comments on commit 65c06fa

Please sign in to comment.