0

This is a section of my code:

if let newValue = change?[NSKeyValueChangeNewKey] {
    print("\(newValue)")
    faceBounds = newValue as? CGRect
    print("\(faceBounds)" + " in controller")
    dispatch_async(dispatch_get_main_queue(),{ () -> Void in self.updateFaceRectView()})
}

where "faceBounds" is a CGRect? type.

However, this is the output from the system I got:

NSRect: {{116.24999, 337.49997}, {86.249992, 86.249992}}

nil in controller

What is happening? Why isn't "faceBounds" getting the correct value?


[UPDATE]

Tried this too,

if let newValue = change?[NSKeyValueChangeNewKey] {
    var str: String?
    str = newValue as? String
    print("\(str)")
    // Still prints nil
}

Is my knowledge with using casting wrong?

And btw if anyone's wondering, newValue is an AnyObject type.

Community
  • 1
  • 1
Ray Tso
  • 566
  • 9
  • 17

3 Answers3

0

As written in the documentation:

AnyObject can represent an instance of any class type.

An NSRect (and CGRect) are struct types not class types so they aren't compatible with AnyObject, so newValue as? CGRect won't work. You might try casting casting to Any first and then try downcasting to CGRect.

let newValue = change?[NSKeyValueChangeNewKey] as! Any
faceBounds = newValue as? CGRect
Aaron
  • 6,466
  • 7
  • 37
  • 75
0

OK, I have found a workaround "for now":

faceBounds = newChange.CGRectValue

This solves the nil problem, but is NOT casting at all. If anyone has a more "casting" like way, please feel free to post your answer.

Ray Tso
  • 566
  • 9
  • 17
0

You can use Foundation's NSRectToCGRect():

if let newValue = change?[NSKeyValueChangeNewKey] {
    print("\(newValue)")
    faceBounds = NSRectToCGRect(newValue)
    print("\(faceBounds)" + " in controller")
    dispatch_async(dispatch_get_main_queue(),{ () -> Void in self.updateFaceRectView()})
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253