Check if class has a value for a key

2.6k Views Asked by At

I know you can set properties of Foundation classes using setValue(value, forKey: key) but how can you check if a class has a value for a key?

2

There are 2 best solutions below

0
On BEST ANSWER

This is annoying problem. In the following code snippet I use reflection to check whether a call to valueForObject is safe. It might have a huge performance penalty ...

The solution was inspired by this blog 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
2
On

Swift3 version of the Raymond's response

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")