最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

[已解决]Swift中用delegate的方法出错:Optional type _?? cannot be used as a boolean test for != nil instead

Swift crifan 1016浏览 0评论

[背景]

折腾:

[已解决]如何把Object-C中的protocol和delegate转为Swift代码

期间,去把代码改为:

protocol RecordTabBarControllerDelegate {
    func shouldSelectViewController(tabBarController:RecordTabBarController, atIndex:UInt) -> Bool
    func didSelectViewController(tabBarController:RecordTabBarController, atIndex:UInt)
}

        if delegate?.shouldSelectViewController(self, atIndex: newSelectedIndex) {

结果出错:

Optional type ‘_??’ cannot be used as a boolean; test for ‘!= nil’ instead

如图:

Optional type cannot be used as a boolean test for nil instead

 

[解决过程]

1.搜:

swift Optional type _?? cannot be used as a boolean test for != nil instead

参考:

ios – Optional type ‘$T11’ cannot be used as a boolean; test for ‘!= nil’ instead since installing XCode 6 beta 7 – Stack Overflow

swift – Checking the value of an Optional Bool – Stack Overflow

感觉此处是:

然后后面的函数虽然是返回bool的,但是先是带了optional的delegate,而optional是不允许去直接判断的

-》因为optional内部实际上是扩展为判断语句的。

swift – Receiving Error "Optional type ‘$T3’ cannot be used as a boolean; test for ‘!=nil’ instead – Stack Overflow

2.算了,加上判断等于true的试试:

        if delegate?.shouldSelectViewController(self, atIndex: newSelectedIndex) == true 

结果还真的通过编译了。

 

[总结]

此处:

         if delegate?.shouldSelectViewController(self, atIndex: newSelectedIndex) {

出错:

Optional type _?? cannot be used as a boolean test for != nil instead

的原因是:

if后面的真值判断语句中包含了optional的delegate

-》带optional的值,是不能隐式判断的,所以需要改为显式的判断,加上==true去判断:

if delegate?.shouldSelectViewController(self, atIndex: newSelectedIndex) == true 

即可。

转载请注明:在路上 » [已解决]Swift中用delegate的方法出错:Optional type _?? cannot be used as a boolean test for != nil instead

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
72 queries in 0.105 seconds, using 18.87MB memory