Taras Shchybovyk Taras Shchybovyk - 1 year ago 189
Swift Question

error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

I have a code that uses KVO functionality.

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
let oldRect = change?[NSKeyValueChangeOldKey] as! NSRect

So when I am trying to cast value to NSRect I am getting the error:

error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

And the object is NSRect type object:

(lldb) po change?[NSKeyValueChangeOldKey]
▿ Optional<AnyObject>
- Some : NSRect: {{293, 21}, {108, 108}}

Answer Source

As you know, the change parameter of observeValueForKeyPath(_:ofObject:change:context:) is of type [String : AnyObject]?, and internally, it's an NSDictionary, which cannot contain NSRange as a value.

So, KVO converts the value to an NSValue containing NSRange. But unfortunately, it cannot be directly bridged to NSRange in Swift.

Try something like this:

    let oldRect = (change?[NSKeyValueChangeOldKey] as! NSValue).rectValue
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download