Issue #10
There is time we want to execute an action only once. We can surely introduce a flag, but it will be nicer if we abstract that out using composition. Then we have
class Once {
var already: Bool = false
func run(@noescape block: () -> Void) {
guard !already else {
return
}
block()
already = true
}
}
Usage
class ViewController: UIViewController {
let once = Once()
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
once.run {
cameraMan.setup()
}
}
}
In the same way, we can check to run a closure when a value changes
final class WhenChange<T: Equatable> {
private(set) var value: T
init(value: T) {
self.value = value
}
func run(newValue: T, closure: (T) -> Void) {
if newValue != value {
value = newValue
closure(value)
}
}
}