我有以下课程
class Appointment: NSObject {
var id:NSString!
var status:NSString!
var clinic:Clinic!
var medicalCase:MedicalCase!
var patient:Patient!
var appointmentDate:NSString!
var reasonForVisit:NSString!
var cancellationReason:NSString!
var visit:NSString!
}
此代码解析nsdisctionary并将值赋给Appointment对象属性
if let appointments:NSArray! = topApps["apointments"] as? NSArray {
dashboardRecord.apointments = NSMutableArray()
for disc in appointments
{
var appointment:Appointment! = Appointment()
if let status: NSString! = disc["status"] as? NSString {
appointment.status = status
}
}
}
现在我想动态地做。而不是像这样做
if let status: NSString! = disc["status"] as? NSString {
appointment.status = status
}
我想动态地执行此操作,下面的代码从光盘中获取值而无需手动写入密钥,但如何将这些值分配给约会对象属性。有没有办法从字符串中获取对象属性?
var properties = appointments.propertyNames()//giving me array of property names.
for key in properties
{
}
想要做一些事情(只是为了解释我想要实现的目标)
约会。[“key”] = disc [key] //约会是约会类的对象
答案 0 :(得分:0)
如果您愿意继承NSObject,可以使用key-value coding。这是一个使用类型检查的例子(在Playground中运行):
class Foo : NSObject {
var bar: NSString! = ""
var boing: NSString! = ""
func parse(input: [NSString : NSObject]) {
// List all the keys that should have string values.
let stringKeys = [ "bar", "boing" ]
for (key, value) in input {
if !key.isKindOfClass(NSString) {
// Safe-guard. We want the keys to always be strings.
continue;
}
if contains(stringKeys, key as String) && value.isKindOfClass(NSString) {
self.setValue(value, forKey: key as String)
}
}
}
}
let f = Foo()
f.parse( [ "bar" : "someValue", "boing" : "anotherValue" ] )
println(f.bar)
println(f.boing)