Skip to content

Instantly share code, notes, and snippets.

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 sindresorhus/9f37a6f6ba5bc7aa31f9ace87d3dc762 to your computer and use it in GitHub Desktop.
Save sindresorhus/9f37a6f6ba5bc7aa31f9ace87d3dc762 to your computer and use it in GitHub Desktop.
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)
}
}
@DevAndArtist
Copy link

@sindresorhus just noticed that you forked my gist. :) Check out the updated version, it contains a very cool upgrade for reactive streams.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment