Reputation: 21
If I have an array "properties" with the properties of my class
public class Circle {
private var properties = ["radius", "diameter", "area", "perimeter"]
public var radius: Double = 0.0
public var diameter: Double = 0.0
public var area: Double = 0.0
public var perimeter: Double = 0.0
is there any way to get the properties' values using the array..?
I tried:
public var description: String {
var str = description()
for label in properties {
let value = label
str += label + "\t\(self.(value))\n"
}
return str
}
but it doesn't work, how can I get the properties, using their names stored in another variable like "value"?
Upvotes: 1
Views: 296
Reputation: 1071
If you can update the class to conform to NSObject, you can use the valueForKey:
method
public class Circle: NSObject {
private var properties = ["radius", "diameter", "area", "perimeter"]
public var radius: Double = 0.0
public var diameter: Double = 0.0
public var area: Double = 0.0
public var perimeter: Double = 0.0
public var description: String {
var str = description()
for label in properties {
let value = value(forKey: label)
str += label + "\t\(label): \(value)\n"
}
return str
}
Upvotes: 1