Passing an argument to dispatch_async

2019-03-02 13:47发布

I'm new to Swift and looking at how the dispatch_async function works. The API doc shows dispatch_async having two parameters. However, I'm able to pass in one argument and it's okay.

dispatch_async(dispatch_get_main_queue()) { 

}

How come I don't need to pass in two arguments?

Thank you,

API Doc:

enter image description here

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-02 14:39

It is a trailing closure syntax

func someFunctionThatTakesAClosure(closure: () -> ()) {
    // function body goes here
}

// here's how you call this function without using a trailing closure:

someFunctionThatTakesAClosure({
    // closure's body goes here
})

// here's how you call this function with a trailing closure instead:

someFunctionThatTakesAClosure() {
    // trailing closure's body goes here
}

https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

查看更多
地球回转人心会变
3楼-- · 2019-03-02 14:40

This is how the dispatch_async looks like..

dispatch_async(dispatch_get_main_queue(), ^{

});

this part

^{

}

is the second parameter to your function, which is an anonymous code block used for callBack implementation.

查看更多
登录 后发表回答