Cosmo
Cosmo

Reputation: 201

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?

Upvotes: 8

Views: 6333

Answers (2)

Cristik
Cristik

Reputation: 32807

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 observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) 

Upvotes: 16

Mark A. Durham
Mark A. Durham

Reputation: 864

This is what (finally) worked for me using Swift 3.0 in Xcode Version 8.0 (8A218a):

@objc
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

Upvotes: 18

Related Questions