ios - 可选链接未按预期工作

标签 ios swift

我的 UIViewController 子类中有以下代码

class SideMenu: UIViewController {

  var contentViewController: UIViewController?

   override func shouldAutorotate() -> Bool {

        return contentViewController?.shouldAutorotate()

    }
}

但由于某种原因,我收到以下错误:

Value of optional type 'Bool?' not unwrapped; did you mean to use '!' or '??'

Screenshot of above error message on the return line

我希望可选链接解开可选,但这似乎不是真的?我错了吗?

最佳答案

可选链的结果是可选的。所以 ?.shouldAutorotate() 产生一个 Bool? 而你的函数需要一个 Bool。因此错误:

Value of optional type 'Bool?' not unwrapped; did you mean to use '!' or '??'

错误概述了两种可能的解决方案。一种是使用 contentViewController!.shouldAutorotate()contentViewController?.shouldAutorotate()! 解包,但如果 contentViewController 是,这两种方法都会崩溃nil 这不是您想要的。

另一种选择是在您的 Bool?nil 时提供回退值。有一个很好的链接运算符:??,它在左侧采用 T?,在右侧采用 T

也就是说,如果你想在 contentViewController 为 nil 时返回 false,你将返回以下内容:

return contentViewController?.shouldAutorotate() ?? false

这实际上与以下代码的行为相同:

if let controller = contentViewController {
    return controller.shouldAutorotate()
} else { 
    return false
}

关于ios - 可选链接未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26262330/

相关文章:

iphone - UIView 调整大小和平移动画不能正确地为 subview 设置动画

ios - 是否可以自定义 Apple iOS TouchID AlertView

iOS 核心数据 - 严重的应用程序错误 - 尝试插入 nil - 不到 1%

ios - 仍与 Google 保持联系

swift - 将 jsonString 添加到 Alamofire 请求

ios - 为什么会有 "potential leak"?

ios - UIAlertView 按钮操作不起作用

ios - 带有自定义单元格的 UITableView 中的数千个 UITableViewCellSeperatorView

ios - 表格 View 中隐藏的自定义范围 slider

ios - 如何在用户登录后自动更新 ViewController