Cosmo Cosmo - 1 year ago 228
iOS Question

Using - observeValueForKeyPath:ofObject:change:context: in Swift 3

I'm trying to convert a Swift 2.2 project to Swift 3, and I'm getting the following error:

Method 'observeValue(forKeyPath:ofObject:change:context:)' with Objective-C selector 'observeValueForKeyPath:ofObject:change:context:' conflicts with method 'observeValue(forKeyPath:of:change:context:)' from superclass 'NSObject' with the same Objective-C selector" for the function call

On my function whose signature is:

func observeValue(forKeyPath keyPath: String?, ofObject: Any?, change: [String : Any]?, context: UnsafeMutableRawPointer?)."

I have read the advice on the Swift 3 Migration Guide web site:

"Workaround: Add an @objc(objectiveC:name:) attribute before the implementation of the optional requirement with the original Objective-C selector inside."

But it isn't clear to me how this is actually supposed to be applied in a source file, and nothing I have tried so far has worked successfully.

Can anyone explain how to set this up properly?

Answer Source

Just start typing observeValueFor... and Xcode will suggest you a valid autocompletion for that. Choose it, and you should be good to go.

Your function then should look something like this:

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download