[背景]
折腾:
[已解决]如何把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
如图:
[解决过程]
1.搜:
swift Optional type _?? cannot be used as a boolean test for != nil instead
参考:
swift – Checking the value of an Optional Bool – Stack Overflow
感觉此处是:
然后后面的函数虽然是返回bool的,但是先是带了optional的delegate,而optional是不允许去直接判断的
-》因为optional内部实际上是扩展为判断语句的。
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