unexpectedly found nil while unwrapping an Optional value keyboardWillShow

后端 未结 2 945
孤独总比滥情好
孤独总比滥情好 2020-12-20 01:47

I have this code below which runs when the keyboardWillShowNotification is called:

func keyboardWillShow(_ notification: Notification) {
    //ERROR IN THE L         


        
2条回答
  •  没有蜡笔的小新
    2020-12-20 02:10

    (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

提交回复
热议问题