如何在Swift中执行一次代码? [英] How do I execute code once and only once in Swift?
问题描述
The answers I've seen so far (1, 2, 3) recommend using GCD's dispatch_once
thus:
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()
输出:
This is printed only on the first call to test()
This is printed for each call to test()
但是请稍等. token
是变量,所以我可以轻松地做到这一点:
But wait a minute. token
is a variable, so I could easily do this:
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()
输出:
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()
如果我们可以更改token
的值,那么dispatch_once
就没有用了!将token
转换为常量并不容易,因为它需要为UnsafeMutablePointer<dispatch_once_t>
类型.
So dispatch_once
is of no use if we I can change the value of token
! And turning token
into a constant is not straightforward as it needs to of type UnsafeMutablePointer<dispatch_once_t>
.
那么我们应该放弃Swift中的dispatch_once
吗?有没有一种安全的方法可以只执行一次代码?
So should we give up on dispatch_once
in Swift? Is there a safer way to execute code just once?
推荐答案
由闭包初始化的静态属性会延迟运行,并且最多运行一次,因此尽管被调用了两次,但它仅打印一次:
Static properties initialized by a closure are run lazily and at most once, so this prints only once, in spite of being called twice:
/*
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.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.
这篇关于如何在Swift中执行一次代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!