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()
Output:
This is printed only on the first call to test()
This is printed for each call to test()
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()
Output:
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()
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>
.
So should we give up on dispatch_once
in Swift? Is there a safer way to execute code just once?
token
in the same scope as thedispatch_once
block (and give it a better name likeonceToken
and place it RIGHT above thedispatch_once
block itself so that it's very clear). – Unfinisheddispatch_once
is no safer than using an ordinary boolean variable. – Malkamalkahdispatch_once
would probably be a much better discussion for Stack Overflow. I'd quite like to see that answer (if it hasn't already been asked & answered here). – Unfinished