Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift function can be called only once

What is the simplest way to write a piece of code that can be executed only once?

I know a way but has a problem.

first, I write a Boolean variable that has negative value but can be set to positive and cannot change after that

 var hasTheFunctionCalled : Bool = false {
   didSet{
       hasTheFunctionCalled = true
   }
} 

and then write the function and the code inside it:

func theFunction(){
   if !hasTheFunctionCalled{
      //do the thing
   }
   hasTheFunctionCalled = true
 } 

but the problem is that the variable can be changed from somewhere else in the scope and this solution doesn't really look so simple and concrete.

like image 249
Hamoonist Avatar asked Feb 02 '18 22:02

Hamoonist


People also ask

How functions are called in Swift?

Every function has a function name, which describes the task that the function performs. To use a function, you "call" that function with its name and pass input values (known as arguments) that match the types of the function's parameters. Function parameters are also called as 'tuples'.

What are the differences between functions and methods in Swift?

Functions are the properties of structured languages. Methods are the properties of Object-oriented language. It is a self-describing piece of code. It is used to manipulate the instance variable of a class.


1 Answers

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.

like image 148
Julien Perrenoud Avatar answered Oct 05 '22 07:10

Julien Perrenoud