0

I have below classs

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!

}

And this code which parsing nsdisctionary and assigning value to Appointment object property

        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
                }
            }

        }

Now i want to do it dynamically. instead of doing like this

          if let status: NSString! = disc["status"] as? NSString {
                appointment.status = status
            }

I want to do it dynamically, below code gives me values from disc without manually writing key but how to assign these values to appointment object properties. is there way to get object property from string?

           var properties = appointments.propertyNames()//giving me array of property names.

            for key in properties
            {

            }

want to do something like(just to explain what i want to achieve)

appointment.["key"] = disc[key] // appointment is object of Appointment class

Vikram Singh
  • 1,726
  • 1
  • 13
  • 25
Dattatray Deokar
  • 1,923
  • 2
  • 21
  • 31

1 Answers1

0

If you're willing to inherit from NSObject, you can use key-value coding for that. Here's an example using type-checking (runs in the 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)
DarkDust
  • 90,870
  • 19
  • 190
  • 224