Search code examples
iosxcodeswift3key-value-observingunsafe-pointers

Swift 3.0 UnsafeMutableRawPointer in Case Switch


Following works in Swift 3.0:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
    {
        if context == &MyContext1 {
        .........
        }
        else if context == &MyContext2 {
        .........
        }
}

However, since I have many conditions, if I use switch/case like this:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
    {
        switch context {
           case &MyContext1 :
                ........
           case &MyContext2 :
                ........
        }
    }

I get an error in regards to UnsafeMutableRawPointer not being able to convert to an integer.

Declarations:

private var MyContext1 = 0
private var MyContext2 = 0

Solution

  • When unwrapping context the code compiles fine:

    private var MyContext1 = 0
    private var MyContext2 = 0
    
    func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        switch context! {
        case &MyContext1 : break
            //
        case &MyContext2 : break
        //
        default: break
        }
    }