Created
August 13, 2025 14:00
-
-
Save hmlongco/0558aee34b609532625779909b0a29b8 to your computer and use it in GitHub Desktop.
LazyState
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// LazyState.swift | |
// Extensions | |
// | |
// Created by Michael Long on 3/5/25. | |
// | |
import Observation | |
import SwiftUI | |
@MainActor | |
@propertyWrapper | |
public struct LazyState<T: Observable>: DynamicProperty { | |
@State private var thunkedValue: ThunkedValue<T> | |
public init(wrappedValue thunk: @autoclosure @escaping () -> T) { | |
_thunkedValue = State(wrappedValue: ThunkedValue(wrappedValue: thunk)) | |
} | |
public var wrappedValue: T { | |
thunkedValue.value | |
} | |
public var projectedValue: Binding<T> { | |
Binding(get: { thunkedValue.value }, set: { _ in }) | |
} | |
} | |
private final class ThunkedValue<T: Observable> { | |
private var object: T! | |
private var thunk: (() -> T)? | |
init(wrappedValue thunk: @escaping () -> T) { | |
self.thunk = thunk | |
} | |
var value: T { | |
if let thunk { | |
object = thunk() | |
self.thunk = nil | |
} | |
return object | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment