I have the following extension
extension UIWindow {
static var key: UIWindow! {
if #available(iOS 13, *) {
return UIApplication.shared.windows.first { $0.isKeyWindow }
} else {
return UIApplication.shared.keyWindow
}
}
}
I can use it without optional chaining in the following case
Case 1
UIWindow.key.addGestureRecognizer(UIGestureRecognizer())
Case 2
let key: UIWindow = UIWindow.key
key.addGestureRecognizer(UIGestureRecognizer())
But, when use it in the following case, I will get a compiler error
Case 3 (Not working)
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())
May I know why it is so? Why the compiler cannot recognise key
as UIWindow
, without having programmer to declare its type explicitly?