mhdhejazi / Dynamic

Call hidden/private API in style! The Swift way.

Home Page:https://medium.com/@mhdhejazi/calling-ios-and-macos-hidden-api-in-style-1a924f244ad1

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Dynamic KeyPath

malhal opened this issue · comments

Just wondering if you library can help with Swift not supporting a dynamic KeyPath, e.g. below the "key" is not a property of an object so the \key syntax cannot be used:

        let dict = NSMutableDictionary(object: "value1", forKey: NSString("key"))
        dict.observe(keyPath:KeyPath("key")) { (dict, change) in // compilation error
            
        }
        dict.setObject("value2", forKey: NSString("key"))

'KeyPath<Root, Value>' cannot be constructed because it has no accessible initializers

This problem is also mentioned on the Swift Forums:
How can I make KeyPath from String? https://forums.swift.org/t/how-can-i-make-keypath-from-string/19658

Actually, no. This is out of the scope of this library.

But you can use the old school style of KVO:

dict.addObserver(self, forKeyPath: "key", options: [], context: nil)
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
  print("changed")
}

And don't forget to removeObserver() at some point.