如何在Swift中执行一次代码只执行一次?

如何在Swift中执行一次代码只执行一次?,第1张

概述到目前为止我所看到的答案( 1, 2, 3)建议使用GCD的dispatch_once: var token: dispatch_once_t = 0func test() { dispatch_once(&token) { print("This is printed only on the first call to test()") } print( 到目前为止我所看到的答案( 1,2,3)建议使用GCD的dispatch_once:
var token: dispatch_once_t = 0func test() {    dispatch_once(&token) {        print("This is printed only on the first call to test()")    }    print("This is printed for each call to test()")}test()

输出:

This is printed only on the first call to test()This is printed for each call to test()

但等一下. token是一个变量,所以我可以很容易地做到这一点:

var token: dispatch_once_t = 0func test() {    dispatch_once(&token) {        print("This is printed only on the first call to test()")    }    print("This is printed for each call to test()")}test()token = 0test()

输出:

This is printed only on the first call to test()This is printed for each call to test()This is printed only on the first call to test()This is printed for each call to test()

因此,如果我可以更改令牌的值,dispatch_once是没用的!将令牌转换为常量并不简单,因为它需要类型为UnsafeMutablePointer< dispatch_once_t>.

那么我们应该放弃Swift中的dispatch_once吗?有一种更安全的方式只执行一次代码吗?

由闭包初始化的静态属性是懒惰运行的,最多只运行一次,所以这只打印一次,尽管被调用了两次:
/*run like:    swift once.swift    swift once.swift runto 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.")}

示例运行:

~/W/WhenDoesstaticDefaultRun> swift once.swiftNote how it's run lazily,so you won't see the "Behold" text Now.~/W/WhenDoesstaticDefaultRun> swift once.swift runBehold! Once runs!Called twice,but only printed "Behold" once,as desired.
总结

以上是内存溢出为你收集整理的如何在Swift中执行一次代码只执行一次?全部内容,希望文章能够帮你解决如何在Swift中执行一次代码只执行一次?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1048374.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存