Skip to content

Instantly share code, notes, and snippets.

@hmlongco
Created August 13, 2025 14:00
Show Gist options
  • Save hmlongco/0558aee34b609532625779909b0a29b8 to your computer and use it in GitHub Desktop.
Save hmlongco/0558aee34b609532625779909b0a29b8 to your computer and use it in GitHub Desktop.
LazyState
//
// 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