-
Notifications
You must be signed in to change notification settings - Fork 27
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
62 additions
and
7 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
60 changes: 60 additions & 0 deletions
60
Sources/OpenSwiftUI/DataAndStorage/ModelData/State/StateObject.swift
This file contains 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
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 | ||
} | ||
} | ||
} |