Created
August 21, 2018 17:20
-
-
Save khawajafarooq/5a775ed0740ad8220e65f13095dc56de to your computer and use it in GitHub Desktop.
Lightweight property observer in swift
This file contains 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
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