【发布时间】:2021-07-21 02:07:01
【问题描述】:
我有以下扩展名
extension UIWindow {
static var key: UIWindow! {
if #available(iOS 13, *) {
return UIApplication.shared.windows.first { $0.isKeyWindow }
} else {
return UIApplication.shared.keyWindow
}
}
}
在以下情况下,我可以在没有可选链接的情况下使用它
案例1
UIWindow.key.addGestureRecognizer(UIGestureRecognizer())
案例2
let key: UIWindow = UIWindow.key
key.addGestureRecognizer(UIGestureRecognizer())
但是,当在以下情况下使用它时,我会得到一个编译器错误
案例 3(不工作)
let key = UIWindow.key
// value of optional type 'UIWindow?' must be unwrapped to refer to member 'addGestureRecognizer' of wrapped base type 'UIWindow'
key.addGestureRecognizer(UIGestureRecognizer())
我可以知道为什么会这样吗?为什么编译器无法将key 识别为UIWindow,而无需程序员显式声明其类型?
【问题讨论】: