There are times we want to run an action just once. It would be nice if we can encapsulate this
dispatch_once
In the Objective-C age, there was dispatch_once that ensures a block of code is run only one time for the lifetime for the application
dispatch_once
is meant to be used for action that runs once and only once
Once
Many times, we just want to make an action run once. Encapsulating this prevents scattered boolean flags, and also make the intention clearer
We can have
class Once {
var already: Bool = false
func run(@noescape block: () -> Void) {
guard !already else { return }
block()
already = true
}
}
Then we can use it like
class ViewController: UIViewController {
let once = Once()
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
once.run {
cameraMan.setup()
}
}
}
❤️ Support my apps ❤️
- Push Hero - pure Swift native macOS application to test push notifications
- PastePal - Pasteboard, note and shortcut manager
- Quick Check - smart todo manager
- Alias - App and file shortcut manager
- My other apps
❤️❤️😇😍🤘❤️❤️
Top comments (0)