dispatch_once after the Swift 3 GCD API changes

后端 未结 9 1658
忘掉有多难
忘掉有多难 2020-11-28 20:48

What is the new syntax for dispatch_once in Swift after the changes made in language version 3? The old version was as follows.

var token: dispa         


        
相关标签:
9条回答
  • 2020-11-28 21:17

    Edit

    @Frizlab's answer - this solution is not guaranteed to be thread-safe. An alternative should be used if this is crucial

    Simple solution is

    lazy var dispatchOnce : Void  = { // or anyName I choose
    
        self.title = "Hello Lazy Guy"
    
        return
    }()
    

    used like

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        _ = dispatchOnce
    }
    
    0 讨论(0)
  • 2020-11-28 21:18

    You can declare a top-level variable function like this:

    private var doOnce: ()->() = {
        /* do some work only once per instance */
        return {}
    }()
    

    then call this anywhere:

    doOnce()
    
    0 讨论(0)
  • 2020-11-28 21:23

    You can still use it if you add a bridging header:

    typedef dispatch_once_t mxcl_dispatch_once_t;
    void mxcl_dispatch_once(mxcl_dispatch_once_t *predicate, dispatch_block_t block);
    

    Then in a .m somewhere:

    void mxcl_dispatch_once(mxcl_dispatch_once_t *predicate, dispatch_block_t block) {
        dispatch_once(predicate, block);
    }
    

    You should now be able to use mxcl_dispatch_once from Swift.

    Mostly you should use what Apple suggest instead, but I had some legitimate uses where I needed to dispatch_once with a single token in two functions and there is not covered by what Apple provide instead.

    0 讨论(0)
提交回复
热议问题