我的 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 '??'
我希望可选链接解开可选,但这似乎不是真的?我错了吗?
最佳答案
可选链的结果是可选的。所以 ?.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/