tambykojak tambykojak - 1 year ago 193
iOS Question

How to get a value from NSValue in Swift?

Here's what I've tried so far

func onKeyboardRaise(notification: NSNotification) {
var notificationData = notification.userInfo
var duration = notificationData[UIKeyboardAnimationDurationUserInfoKey] as NSNumber
var frame = notificationData[UIKeyboardFrameBeginUserInfoKey]! as NSValue
var frameValue :UnsafePointer<(CGRect)> = nil;

But I always seem to crash at

It's a little bit confusing because the documentation for
says it returns a
object, but when I log
in the console, it states something like
NSRect {{x, y}, {w, h}}

Answer Source

getValue() must be called with a pointer to an (initialized) variable of the appropriate size:

var frameValue = CGRect(x: 0, y: 0, width: 0, height: 0)

But it is simpler to use the convenience method:

let frameValue = frame.CGRectValue() // Swift 1, 2
let frameValue = frame.cgRectValue() // Swift 3