Swift: Return boolean in GCD Completion Block

巧了我就是萌 提交于 2019-12-13 07:35:19

问题


I have a function written in Swift. I want the completion block to return a boolean. How can I go about doing this? I am using Grand Central Dispatch.

func myFunc() -> Bool 
{
    var success:Bool = false 

    // code here 

    dispatch_async(dispatch_get_main_queue(), { 
        return success
        )}
    )}
}

thanks!


回答1:


Standard why of dealing with this async nature is not to return value, but pass in completion handler:

func myFunc(completion:(success: Bool) -> ()) {
    var success:Bool = false

    // code here

    dispatch_async(dispatch_get_main_queue()) {
        completion(success: success)
    }
}

Then work with it:

myFunc({ (success) in
    // ...
})


来源:https://stackoverflow.com/questions/26847344/swift-return-boolean-in-gcd-completion-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!