由闭包初始化的静态属性是延迟运行的,最多只能运行一次,因此尽管被调用了两次,但它仅打印一次:
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 runBehold! once runs!Called twice, but only printed "Behold" once, as desired.
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)