Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何在Swift中执行一次代码只执行一次?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_489_1@

概述

到目前为止我所看到的答案( 1, 2, 3)建议使用GCD的dispatch_once: var token: dispatch_once_t = 0 func 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 = 0
func 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()@H_616_16@ 
 

输出

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

但等一下. token是一个变量,@R_368_9447@很容易地做到这一点:

var token: dispatch_once_t = 0
func 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 = 0

test()@H_616_16@ 
 

输出

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()@H_616_16@ 
 

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

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

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

示例运行:

~/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.@H_616_16@

大佬总结

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

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。