How to Execute Code Once and Only Once in Swift

How do I execute code once and only once in Swift?

Static properties initialized by a closure are run lazily and at most once, so this prints only once, in spite of being called twice:

/*
run like:

swift once.swift
swift once.swift run

to see both cases
*/
class Once {
static let run: Void = {
print("Behold! \(__FUNCTION__) runs!")
return ()
}()
}

if Process.arguments.indexOf("run") != nil {
let _ = Once.run
let _ = Once.run
print("Called twice, but only printed \"Behold\" once, as desired.")
} else {
print("Note how it's run lazily, so you won't see the \"Behold\" text now.")
}

Example runs:

~/W/WhenDoesStaticDefaultRun> swift once.swift
Note how it's run lazily, so you won't see the "Behold" text now.
~/W/WhenDoesStaticDefaultRun> swift once.swift run
Behold! Once runs!
Called twice, but only printed "Behold" once, as desired.

Swift function can be called only once

A simple solution is to take advantage of lazy variables in the following way:

// Declare your "once-only" closure like this
private lazy var myFunction: Void = {
// Do something once
}()

...

// Then to execute it, just call
_ = myFunction

This ensures that the code inside the myFunction closure is only executed the first time that the program runs _ = myFunction


Edit: Another approach is to use so called "dispatch once tokens". This comes from Objective-C and was available in Swift until Swift 3. It is still possible to make it work, however you will need to add a little bit of custom code. You can find more information on this post -> dispatch_once after the Swift 3 GCD API changes


Edit2: Should be _ = myFunction and not _ = myFunction(), as JohnMontgomery pointed out.

How can I run a piece of code only once in swift?

What you need is persistence between app launches. Fortunately, this exists and is provided with NSUserDefaults.

I would do something like the following in your app delegate didFinishLaunching method:

let hasLaunchedKey = "HasLaunched"
let defaults = UserDefaults.standard
let hasLaunched = defaults.bool(forKey: hasLaunchedKey)

if !hasLaunched {
defaults.set(true, forKey: hasLaunchedKey)
}

// Use hasLaunched

The first time you run the app, the key will not be in the defaults database and will return false. Since it is false, we save the value of true in the defaults database, and each subsequent run you will get a value of true.

Run code only once

You can use dispatch_once in your viewDidLoad:

static dispatch_once_t once;
dispatch_once(&once, ^
{
// Code to run once
});

This will make the code run only once until you exit and close your app.

Call Function only once in UIViewController, iOS Swift4.2, Xcode10.1

If you want to call that PopView function only once in you App then try this,

In App delegate, set bool value

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UserDefaults.standard.set(true, forKey: "showPop") // like so
return true
}

Then, in first view controller try this,

  func hasLaunchPop() {
let isshowPop: Bool = UserDefaults.standard.bool(forKey: "showPop")
if isshowPop == true {
popView()
UserDefaults.standard.set(false, forKey: "showPop")
}
}

then in viewdidload call like this,

override func viewDidLoad() {
super.viewDidLoad()
hasLaunchPop()
}

So that PopView appears only once in your app when its launched and will never show up again.



Related Topics



Leave a reply



Submit