Check if the class has a value for the key
3 answers
This is an annoying problem. In the following code snippet, I am using reflection to check if the call to valueForObject is safe. This can have a huge performance penalty ...
The solution was inspired by this post
extension NSObject {
func safeValueForKey(key: String) -> AnyObject? {
let copy = reflect (self)
for index in 0 ..< copy.count {
let (fieldName, fieldMirror) = copy[index]
if (fieldName == key ){
return valueForKey(fieldName)
}
}
return nil
}
}
class A:NSObject {
var name: String = "Awesome"
}
var a = A()
a.safeValueForKey("name") // "Awesome"
a.safeValueForKey("b") // nil
+1
source to share
Swift3 version of Raymond's answer
extension NSObject {
func safeValue(forKey key: String) -> Any? {
let copy = Mirror(reflecting: self)
for child in copy.children.makeIterator() {
if let label = child.label, label == key {
return child.value
}
}
return nil
}
}
class A:NSObject {
var name: String = "Awesome"
}
var a = A()
a.safeValue(forKey: "name") // "Awesome"
a.safeValue(forKey: "b")
+3
source to share