如何在Swift中执行一次代码?
到目前为止,我已经看到了这些问题的答案2,)建议使用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 = 0
test()
输出:
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
是没有用的,如果我们我可以改变的价值token
!转换token
成常量并非易事,因为它需要类型化UnsafeMutablePointer<dispatch_once_t>
。
那么我们应该放弃dispatch_once
Swift吗?有没有一种安全的方法可以只执行一次代码?
回答:
由闭包初始化的静态属性是延迟运行的,最多只能运行一次,因此尽管被调用了两次,但它仅打印一次:
/*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.")
}
示例运行:
~/W/WhenDoesStaticDefaultRun> swift once.swiftNote 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中执行一次代码? 的全部内容, 来源链接: utcz.com/qa/433198.html