Swift函数只能调用一次

Ham*_*dar 3 static lazy-loading function grand-central-dispatch swift

编写一段只能执行一次的代码的最简单方法是什么?

我知道一种方法但有问题.

首先,我写了一个布尔变量,它具有负值,但可以设置为正值,之后不能更改

 var hasTheFunctionCalled : Bool = false {
   didSet{
       hasTheFunctionCalled = true
   }
} 
Run Code Online (Sandbox Code Playgroud)

然后在其中编写函数和代码:

func theFunction(){
   if !hasTheFunctionCalled{
      //do the thing
   }
   hasTheFunctionCalled = true
 } 
Run Code Online (Sandbox Code Playgroud)

但问题是变量可以从范围内的其他地方更改,这个解决方案看起来并不那么简单和具体.

Jul*_*oud 12

一个简单的解决方案是以lazy下列方式利用变量:

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

...

// Then to execute it, just call
_ = myFunction
Run Code Online (Sandbox Code Playgroud)

这可确保myFunction闭包内的代码仅在程序第一次运行时执行_ = myFunction


编辑:另一种方法是使用所谓的"dispatch once token".它来自Objective-C,在Swift中可用,直到Swift 3.它仍然可以使它工作,但是你需要添加一些自定义代码.您可以在Swift 3 GCD API更改后找到有关此帖子的更多信息 - > dispatch_once


编辑2:应该是_ = myFunction和不是_ = myFunction(),正如JohnMontgomery指出的那样.

  • 不应该只是`_ = myFunction`没有`()`? (3认同)

And*_*ini 8

您可以在嵌套到函数本身的结构中使用静态 bool ,这样做:

func theFunction(){
    struct Holder { static var called = false }

    if !Holder.called {
        Holder.called = true
        //do the thing
    }
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*n R 5

一种可能的技术是将代码放入静态类型属性的初始值设定项中,保证仅延迟初始化一次(即使同时跨多个线程访问):

func theFunction() {
    struct Once {
        static let once = Once()
        init() {
            print("This should be executed only once during the lifetime of the program")
        }
    }
    _ = Once.once
}
Run Code Online (Sandbox Code Playgroud)

(比较“使用 Swift 与 Cocoa 和 Objective-C”参考中的Singleton。)

例子:

print("Call #1")
theFunction()
print("Call #2")
theFunction()
print("Done")
Run Code Online (Sandbox Code Playgroud)

输出:

呼叫 #1
这应该在程序的生命周期内只执行一次
呼叫#2
完毕