How to set the value for key which type is basic data type in runtime in swift?

970 views Asked by At

Just like the topic says, there is a class, I want to set values for the properties in runtime, and I have set the values which are inherited from NSObject use KVC mechanism and Reflect mechanism, and I also need to set values for those who haven't inherited from NSObject, such as dataType is Int, Double. How can I make it?

1

There are 1 answers

3
ewcy On

The signature of setValue(value: Any?, forKey: String) takes Any? instead of AnyObject?. So it's not necessary for that value to be an NSObject subclass.

class MyClass : NSObject {
    public var intField : Int = 100;
    public var doubleField : Double = 10.0;
}

let a = MyClass()
a.setValue(200, forKey: "intField")
a.setValue(20.0, forKey: "doubleField")

print(a.intField) // Output: 200\n
print(a.doubleField) // Output: 20.0\n