Skip to content

Instantly share code, notes, and snippets.

@woodycatliu
Created July 24, 2021 05:11
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 woodycatliu/cc2927a1e423ef63986c8f6fc76ae67c to your computer and use it in GitHub Desktop.
Save woodycatliu/cc2927a1e423ef63986c8f6fc76ae67c to your computer and use it in GitHub Desktop.
這是從 https://github.com/ailabstw/social-distancing-ios 搬運出來的 Observed 屬性包裝器
import Foundation
@propertyWrapper
public class Notified<Value: Equatable> {
public let notificationName: Notification.Name
public var wrappedValue: Value {
didSet {
if oldValue != wrappedValue {
NotificationCenter.default.post(name: notificationName, object: nil)
}
}
}
public var projectedValue: Notified<Value> { self }
public init(wrappedValue: Value, notificationName: Notification.Name) {
self.wrappedValue = wrappedValue
self.notificationName = notificationName
}
public func callAsFunction(using block: @escaping () -> Void) -> NSObjectProtocol {
NotificationCenter.default.addObserver(forName: notificationName, object: nil, queue: nil) { _ in
block()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment