How to execute an action only once in Swift

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

1
2
3
4
5
6
7
8
9
10
11
12
13
class Once {

var already: Bool = false

func run(@noescape block: () -> Void) {
guard !already else {
return
}

block()
already = true
}
}

Usage

1
2
3
4
5
6
7
8
9
10
11
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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)
}
}
}

Comments