Usage - observValueForKeyPath: ofObject: change: context: in Swift 3

I try to convert a Swift 2.2 project to Swift 3 and I get 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 

In my function, whose signature is:

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

I read the tip on the Swift 3 translation guide website:

"Workaround: Add the @objc attribute (objectC: name :) before implementing the optional requirement using the Objective-C selector inside."

But I don’t understand how it should be applied in the source file, and none of what I have tried so far has worked successfully.

Can someone explain how to properly configure it?

+8
ios cocoa swift swift3
source share
2 answers

Just start typing observeValueFor... and Xcode to offer you a valid autocomplete for this. Pick it, and you should be good to go.

Your function should look something like this:

 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) 
+16
source share

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?) { 
+18
source share

All Articles