如何在Swift中执行一次代码?

如何在Swift中执行一次代码?,第1张

如何在Swift中执行一次代码?

由闭包初始化的静态属性是延迟运行的,最多只能运行一次,因此尽管被调用了两次,但它仅打印一次:

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.


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5622482.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存