dispatch_after - GCD in Swift?

前端 未结 25 2395
心在旅途
心在旅途 2020-11-21 06:07

I\'ve gone through the iBook from Apple, and couldn\'t find any definition of it:

Can someone explain the structure of dispatch_after?

d         


        
25条回答
  •  独厮守ぢ
    2020-11-21 06:37

    I use dispatch_after so often that I wrote a top-level utility function to make the syntax simpler:

    func delay(delay:Double, closure:()->()) {
        dispatch_after(
            dispatch_time(
                DISPATCH_TIME_NOW,
                Int64(delay * Double(NSEC_PER_SEC))
            ),
            dispatch_get_main_queue(), closure)
    }
    

    And now you can talk like this:

    delay(0.4) {
        // do stuff
    }
    

    Wow, a language where you can improve the language. What could be better?


    Update for Swift 3, Xcode 8 Seed 6

    Seems almost not worth bothering with, now that they've improved the calling syntax:

    func delay(_ delay:Double, closure:@escaping ()->()) {
        let when = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
    }
    

提交回复
热议问题