Whither dispatch_once in Swift 3?

前端 未结 7 1616
再見小時候
再見小時候 2020-11-27 04:16

Okay, so I found out about the new Swifty Dispatch API in Xcode 8. I\'m having fun using DispatchQueue.main.async, and I\'ve been browsing around the Disp

7条回答
  •  感动是毒
    2020-11-27 05:01

    According to the Migration Guide:

    The free function dispatch_once is no longer available in Swift. In Swift, you can use lazily initialized globals or static properties and get the same thread-safety and called-once guarantees as dispatch_once provided.

    Example:

      let myGlobal = { … global contains initialization in a call to a closure … }()
    
      // using myGlobal will invoke the initialization code only the first time it is used.
      _ = myGlobal  
    

提交回复
热议问题