DEV Community

Khoa Pham
Khoa Pham

Posted on • Edited on

2 1

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

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 ❤️

❤️❤️😇😍🤘❤️❤️

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more