Skip to content

Instantly share code, notes, and snippets.

@khawajafarooq
Created August 21, 2018 17:20
Show Gist options
  • Save khawajafarooq/5a775ed0740ad8220e65f13095dc56de to your computer and use it in GitHub Desktop.
Save khawajafarooq/5a775ed0740ad8220e65f13095dc56de to your computer and use it in GitHub Desktop.
Lightweight property observer in swift
final class Notifiable<T> {
typealias CompletionHandler = ((T) -> ())
private var propertyChanged: CompletionHandler? = nil
var value: T {
didSet {
guard let observer = propertyChanged else { return }
observer(value)
}
}
init(value: T) {
self.value = value
}
func observe(_ completion: @escaping CompletionHandler) {
propertyChanged = completion
}
deinit {
propertyChanged = nil
}
}
// In action
let someValue = Notifiable<String>(value: "Hello World")
someValue.observe { value in
print("value is changed = \(value)")
}
someValue.value = "Hello Farooq"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment