DEV Community

Khoa Pham
Khoa Pham

Posted on • Updated on

How to run action once in Swift

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


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


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 }

    already = true

Then we can use it like

class ViewController: UIViewController {
  let once = Once()

  override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated) {

❤️ Support my apps ❤️


Top comments (0)