Contents
  1. 1. dispatch_once
  2. 2. Once

There are times we want to run an action just once. It would be nice if we can encapsulate this

dispatch_once

dispatch_once is meant to be used for action that runs once and only once

Once

We can have

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

var already: Bool = false

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

block()
already = true
}
}

Then we can use it like

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()
}
}
}
Contents
  1. 1. dispatch_once
  2. 2. Once