Handle valueForUndefinedKey thrown exception in Swift

I have a third-party library class whose source is not open to me. For example, for example:

class MyClass: NSObject { let myProperty = 10 } 

I can get myProperty value like this.

 let test = MyClass().value(forKey: "myProperty") // 10 

I want to check if myProperty in MyClass . The reason is that I do not want my application to crash if an implementation of a third-party class is implemented in the future.

For testing, I tried

 guard let test = MyClass().value(forKey: "myProperty1") else { return } // crash 

 if let test = MyClass().value(forKey: "myProperty1") { } // crash 

 do { let test = try MyClass().value(forKey: "myProperty1") // crash } catch { } 

In every way I get a crash.

*** Application termination due to the unannounced exception "NSUnknownKeyException", reason: "[<__ lldb_expr_80.MyClass 0x608000223a00> valueForUndefinedKey:]: this class is not a key value compatible with the encoding for the key myProperty1. '

+5
source share
1 answer

You should find the best solution by talking to lib dev

You can use Mirror reflection and check its object label

 let myClass = Mirror(reflecting: MyClass()) for (_, attr) in myClass.children.enumerated() { if let propertyName = attr.label, propertyName == "myProperty"{ print(propertyName, attr.value) } } 
+1
source

Source: https://habr.com/ru/post/1261896/


All Articles