unexpectedly found nil while unwrapping an Optional value keyboardWillShow

♀尐吖头ヾ 提交于 2019-11-29 11:56:43

From the docs:

let UIKeyboardFrameEndUserInfoKey: String 

Description

The key for an NSValue object containing a CGRect that identifies the end frame of the keyboard in screen coordinates

Your second key:

let UIKeyboardAnimationDurationUserInfoKey: String

Description The key for an NSNumber object containing a double that identifies the duration of the animation in seconds.

So you need to cast the first one to NSValue and the second one to NSNumber:

func keyboardWillShow(_ notification: Notification) {
    print("keyboardWillShow")
    guard let userInfo = notification.userInfo else { return }
    keyboard = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    animaton = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
    // your code
}

(How to fix your issue is clearly written in Leo Dabus's answer, so I will try to explain the error I was getting before I added the ! .)

In Swift 3, as AnyObject has become one of the most risky operation. It's related to the worst new feature called as id-as-Any.

In this line of your code:

    keyboard = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue

The type of expression notification.userInfo?[UIKeyboardFrameEndUserInfoKey] is Any?. As you see, an Optional type Any? should not be safely converted to non-Optional AnyObject. But Swift 3 converts it with creating non-Optional _SwiftValue.

You can check this behaviour with inserting this code:

print(type(of: notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject))

So, you are trying to apply non-optional-chaining .cgRectValue to _SwiftValue, which may be confusing the Swift 3's feature: "implicit type conversion _SwiftValue back to the Swift value".

Getting too long...


Do NOT use as AnyObject casting in Swift 3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!