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

❤️❤️😇😍🤘❤️❤️

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

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay