Skip to content

Commit

Permalink
Add StateObject implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Kyle-Ye committed Nov 5, 2023
1 parent 3e058c1 commit 7899928
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import Combine
#else
import OpenCombine
#endif
internal import OpenSwiftUIShims

@propertyWrapper
@frozen
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,11 @@ public struct State<Value> {
}
return Binding(value: value, location: _location)
}


}

extension State: DynamicProperty {
// TODO
// public static func _makeProperty(in _: inout _DynamicPropertyBuffer, container _: _GraphValue<some Any>, fieldOffset _: Swift.Int, inputs _: inout _GraphInputs) {
//
// }
// TODO:
public static func _makeProperty(in _: inout _DynamicPropertyBuffer, container _: _GraphValue<some Any>, fieldOffset _: Swift.Int, inputs _: inout _GraphInputs) {}
}

extension State where Value: ExpressibleByNilLiteral {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
//
// StateObject.swift
// OpenSwiftUI
//
// Created by Kyle on 2023/11/5.
// Lastest Version: iOS 15.5
// Status: Blocked by DynamicProperty

#if OPENSWIFTUI_USE_COMBINE
import Combine
#else
import OpenCombine
#endif

@frozen
@propertyWrapper
public struct StateObject<ObjectType> where ObjectType: ObservableObject {
@usableFromInline
@frozen
enum Storage {
case initially(() -> ObjectType)
case object(ObservedObject<ObjectType>)
}

@usableFromInline
var storage: StateObject<ObjectType>.Storage

@inlinable
public init(wrappedValue thunk: @autoclosure @escaping () -> ObjectType) {
storage = .initially(thunk)
}

public var wrappedValue: ObjectType {
objectValue.wrappedValue
}

public var projectedValue: ObservedObject<ObjectType>.Wrapper {
objectValue.projectedValue
}
}

extension StateObject: DynamicProperty {
public static func _makeProperty(in _: inout _DynamicPropertyBuffer, container _: _GraphValue<some Any>, fieldOffset _: Int, inputs _: inout _GraphInputs) {
// TODO:
}

public static var _propertyBehaviors: UInt32 { 2 }
}

extension StateObject {
var objectValue: ObservedObject<ObjectType> {
switch storage {
case let .initially(thunk):
Log.runtimeIssues("Accessing StateObject's object without being installed on a View. This will create a new instance each time.")
return ObservedObject(wrappedValue: thunk())
case let .object(value):
return value
}
}
}

0 comments on commit 7899928

Please sign in to comment.