0
func keyboardDidShow(notification:NSNotification) {

    var info = notification.userInfo
    var keyboardHeight: CGFloat = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue().size.height
    constraintScrollViewBottomSpace.constant = keyboardHeight
}

The above code is giving me the error

Could not find an overload for 'subscript' that accepts the supplied arguments

What should I do to make it work?

var info = notification.userInfo!

Adding ! resolved the error. But what is reason for it. Explain.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
PK86
  • 1,218
  • 2
  • 14
  • 25

2 Answers2

2

If you don't add ! , info is an optional. And optionals don't have that method. You have to understand that optional variables are of totally different type. You have to unwrap them to get the behaviour of the type you are expecting(after unwrapping).

E.g.

var str = String?

Here str is not a String which can be nil, but str is a Optional which can be String when not nil.(Statement by Paul Hegarty, CS 193P)

So if you want to use the methods of String , you have to first unwrap the variable to make it of String type, otherwise str will be an Optional

saurabh
  • 6,687
  • 7
  • 42
  • 63
1

In Swift, userInfo is of type [NSObject : AnyObject]?

That's an optional containing a dictionary with a key of type NSObject and a value of AnyObject.

If you are storing an array in the userInfo parameter instead then you'll have to figure out how to cast it to the correct type (and unwrap the optional). Swift doesn't like casting from a type to an incompatible type, and I'm not expert enough with the language yet to tell you how to do it. I'd have to flog at it for a while in Xcode.

Why not store a dictionary in userInfo that contains your array? That's easy to do, and follows the pattern you're supposed to use with passing data in an NSNotification's userInfo property.

Duncan C
  • 128,072
  • 22
  • 173
  • 272