Search code examples
swiftfoundation

Check if class has a value for a key


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?


Solution

  • 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