Error: Bool is not Convertible to Void:

2019-02-13 07:18发布

I am moving my code from Obj. C to Swift C and trying to implementing the Twitter sdk..

But, I am getting an error... Can any body tell me what I have done wrong.

enter image description here

Please help me with this.

I spent 2 days tried everything but didn't work for me.

3条回答
祖国的老花朵
2楼-- · 2019-02-13 07:35

The problem is that openURL returns a boolean, and an attempt to convert it to Void is made, since the closure is declared as returning a Void. Simply remove that as follows:

{ (url: NSURL, token: String)  in
    UIApplication.sharedApplication().openURL(url)
}

If you don't want to change the closure signature, just assign the return value to a variable:

{ (url: NSURL, token: String) -> Void in
    let ret = UIApplication.sharedApplication().openURL(url)
}
查看更多
孤傲高冷的网名
3楼-- · 2019-02-13 07:39

Your block does not have a return statement, therefore the compiler uses the result of the last statement

UIApplication.sharedApplication().openURL(url)

as return value, which is a Bool and not Void as declared in the block signature.

To solve that problem, just add a return statement:

{ (url: NSURL, oauthToken: String) -> Void in
    UIApplication.sharedApplication().openURL(url)
    return
}
查看更多
迷人小祖宗
4楼-- · 2019-02-13 07:44

What's not stated in the other answers is that Swift will implicitly add a return to a single statement closure.

This is how statements like conditionSet.sort {$0.set < $1.set} can work.

This can also result in an unexpected error. To avoid the error, make the closure have 2 statements. The simplest way is to add a return after your original statement as stated in the accepted answer.

查看更多
登录 后发表回答