Skip to content

Instantly share code, notes, and snippets.

@DevAndArtist
Created August 11, 2022 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DevAndArtist/d67560739ee5599a09f4f84f9f3cb8b7 to your computer and use it in GitHub Desktop.
Save DevAndArtist/d67560739ee5599a09f4f84f9f3cb8b7 to your computer and use it in GitHub Desktop.
import SwiftUI
extension EnvironmentValues {
struct UnconstrainedObjectKey<Object>:
EnvironmentKey
where
Object: AnyObject
{
static var defaultValue: Object? {
nil
}
}
subscript <Object>() -> Object? where Object: AnyObject {
get {
self[UnconstrainedObjectKey<Object>.self]
}
set {
self[UnconstrainedObjectKey<Object>.self] = newValue
}
}
}
@propertyWrapper
public struct UnconstrainedEnvironmentObject<ObjectType>:
DynamicProperty
where
ObjectType: ObservableObject
{
@Environment(\.[])
var _object: ObjectType?
@dynamicMemberLookup
public struct Wrapper {
let object: ObjectType
public subscript <Subject>(
dynamicMember keyPath: ReferenceWritableKeyPath<ObjectType, Subject>
) -> Binding<Subject> {
Binding(
get: {
object[keyPath: keyPath]
},
set: { newValue in
object[keyPath: keyPath] = newValue
}
)
}
}
public var wrappedValue: ObjectType {
guard let object = _object else {
fatalError("Object of type '\(ObjectType.self)' not found")
}
return object
}
public var projectedValue: Wrapper {
Wrapper(object: wrappedValue)
}
public init() {}
}
extension View {
public func unconstrainedEnvironmentObject<T>(
_ object: T
) -> some View where T: ObservableObject {
environment(\.[], object)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment