Created
August 12, 2014 16:25
-
-
Save kristopherjohnson/7522f92bb5c4b667d506 to your computer and use it in GitHub Desktop.
Example of using dispatch_once() in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
var token: dispatch_once_t = 0 | |
func test() { | |
dispatch_once(&token) { | |
println("This is printed only on the first call to test()") | |
} | |
println("This is printed for each call to test()") | |
} | |
for _ in 0..<4 { | |
test() | |
} | |
/* Output: | |
This is printed only on the first call to test() | |
This is printed for each call to test() | |
This is printed for each call to test() | |
This is printed for each call to test() | |
This is printed for each call to test() | |
*/ |
In Swift 3 something like this:
class Test {
static let once: Void = {
print("only first time")
}()
func hi() {
Test.once
print("every time")
}
}
let test = Test()
for i in 0..<3 {
test.hi()
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Swift 3 extension:
Usage: