Skip to content

Commit

Permalink
Slightly improve performance of State
Browse files Browse the repository at this point in the history
  • Loading branch information
david-swift committed Apr 21, 2024
1 parent 795410d commit 7748668
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
2 changes: 1 addition & 1 deletion Sources/Adwaita/Model/Data Flow/Binding.swift
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ extension Binding where Value: MutableCollection {
public subscript(safe index: Value.Index?, default defaultValue: Value.Element) -> Binding<Value.Element> {
.init {
if let index, wrappedValue.indices.contains(index) {
return wrappedValue[index] ?? defaultValue
return wrappedValue[index]
}
return defaultValue
} set: { newValue in
Expand Down
33 changes: 30 additions & 3 deletions Sources/Adwaita/Model/Data Flow/State.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,22 +72,49 @@ public struct State<Value>: StateProtocol {
/// - wrappedValue: The wrapped value.
/// - forceUpdates: Whether to force update all available views when the property gets modified.
public init(wrappedValue: Value, forceUpdates: Bool = false) {
content = .init(storage: .init(value: wrappedValue))
content = .init(initialValue: wrappedValue)
self.forceUpdates = forceUpdates
}

/// A class storing the state's content.
public class Content {

/// The storage.
public var storage: Storage
public var storage: Storage {
get {
if let internalStorage {
return internalStorage
}
let storage = Storage(value: initialValue)
internalStorage = storage
return storage
}
set {
internalStorage = newValue
}
}
/// The internal storage.
var internalStorage: Storage?
/// The initial value.
private var initialValue: Value

/// Initialize the content.
/// - Parameter storage: The storage.
@available(*, deprecated, message: "Use a safer initializer instead")
public init(storage: Storage) {
// swiftlint:disable force_cast
let initialValue = storage.value as! Value
// swiftlint:enable force_cast
self.initialValue = initialValue
self.storage = storage
}

/// Initialize the content.
/// - Parameter initialValue: The initial value.
public init(initialValue: Value) {
self.initialValue = initialValue
}

}

/// A class storing the value.
Expand Down Expand Up @@ -156,7 +183,7 @@ extension State where Value: Codable {
///
/// The folder path will be appended to the XDG data home directory.
public init(wrappedValue: Value, _ key: String, folder: String? = nil, forceUpdates: Bool = false) {
content = .init(storage: .init(value: wrappedValue))
content = .init(initialValue: wrappedValue)
self.forceUpdates = forceUpdates
content.storage.key = key
content.storage.folder = folder
Expand Down

0 comments on commit 7748668

Please sign in to comment.