ma11hew28
ma11hew28

Reputation: 126477

Swift: NSNumber is not a subtype of UIViewAnimationCurve

How do I get the line below to compile?

UIView.setAnimationCurve(userInfo[UIKeyboardAnimationCurveUserInfoKey].integerValue)

Right now, it gives the compile error:

'NSNumber' is not a subtype of 'UIViewAnimationCurve'

Why does the compiler think userInfo[UIKeyboardAnimationCurveUserInfoKey].integerValue is an NSNumber when integerValue is declared as an Int?

class NSNumber : NSValue {
    // ...
    var integerValue: Int { get }`?
    // ...
}

I've had similar issues with other enum types. What is the general solution?

Upvotes: 6

Views: 6388

Answers (4)

Varun Naharia
Varun Naharia

Reputation: 5428

My solution is

UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: notification.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue)!)

Upvotes: 0

Ryan
Ryan

Reputation: 5496

I used the below code to construct an animation curve value from the user info dictionary:

let rawAnimationCurveValue = (userInfo[UIKeyboardAnimationCurveUserInfoKey] as NSNumber).unsignedIntegerValue
let keyboardAnimationCurve = UIViewAnimationCurve(rawValue: rawAnimationCurveValue)

Upvotes: 2

ma11hew28
ma11hew28

Reputation: 126477

UIView.setAnimationCurve(UIViewAnimationCurve.fromRaw(userInfo[UIKeyboardAnimationCurveUserInfoKey].integerValue)!)

Read more: Swift enumerations & fromRaw()

UPDATE

Based on this answer to How to use the default iOS7 UIAnimation curve, I use the new block-based animation method, + animateWithDuration:delay:options:animations:completion:, and get the UIViewAnimationOptions like so:

let options = UIViewAnimationOptions(UInt((userInfo[UIKeyboardAnimationCurveUserInfoKey] as NSNumber).integerValue << 16))

Upvotes: 13

David Berry
David Berry

Reputation: 41236

You have two problems:

  1. Optional numbers may be represented as NSNumbers and the result of any subscript operation should be an optional. In this case integerValue isn't an integer, it's an optional integer (the trailing '?')

  2. Enums aren't interchangeable with integers.

Try:

UIAnimationCurve(userInfo[UIAnimationCurveUserInfoKey]?)

Upvotes: 0

Related Questions