Whither dispatch_once in Swift 3?

前端 未结 7 1600
再見小時候
再見小時候 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 04:53

    While the "lazy var" pattern allows me to stop caring about dispatch tokens and is generally more convenient than dispatch_once() was, I don't like how it looks at call site:

    _ = doSomethingOnce
    

    I would expect this statement to look more like a function call (since it implies action), but it doesn't look so at all. Also, having to write _ = to explicitly discard the result is unnecessary and annoying.

    There is a better way:

    lazy var doSomethingOnce: () -> Void = {
      print("executed once")
      return {}
    }()
    

    Which makes the following possible:

    doSomethingOnce()
    

    This might be less efficient (since it calls an empty closure instead of just discarding a Void), but improved clarity is totally worth it for me.

提交回复
热议问题