Forked from DevAndArtist/swiftui_helper_property_wrapper.swift
Created
January 20, 2020 04:13
-
-
Save sindresorhus/9f37a6f6ba5bc7aa31f9ace87d3dc762 to your computer and use it in GitHub Desktop.
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
import Combine | |
import SwiftUI | |
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) | |
@propertyWrapper | |
public struct Model<Value>: DynamicProperty { | |
private final class _Box: ObservableObject { | |
let objectWillChange = ObservableObjectPublisher() | |
var value: Value { | |
willSet { | |
objectWillChange.send() | |
} | |
} | |
init(value: Value) { | |
self.value = value | |
} | |
} | |
@ObservedObject | |
private var _box: _Box | |
public init(wrappedValue value: Value) { | |
// Substituted by the compiler with: | |
// `self.__box = ObservedObject(wrappedValue: _Box(value: value))` | |
self._box = _Box(value: value) | |
} | |
public var wrappedValue: Value { | |
get { | |
_box.value | |
} | |
nonmutating set { | |
_box.value = newValue | |
} | |
} | |
public var projectedValue: Binding<Value> { | |
$_box.value | |
} | |
public mutating func update() { | |
__box.update() | |
} | |
} | |
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) | |
extension Model where Value : ExpressibleByNilLiteral { | |
public init() { | |
self._box = _Box(value: nil) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@sindresorhus just noticed that you forked my gist. :) Check out the updated version, it contains a very cool upgrade for reactive streams.