Check if the class has a value for the key

I know you can set properties of Foundation classes with setValue(value, forKey: key)

, but how can you check if a class has a value for a key?

+3


source to share


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


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


valueForKey (key: String) is the name of the func.

class A:NSObject {
    var name: String = ""
}

var a = A()

a.setValue("John", forKey: "name")
a.valueForKey("name") //returns an optional value (AnyObject)

      

0


source







All Articles