lundi 11 juillet 2016

Swift. Refer to instance variables by string name

I've got a number of user properties in a user viewcontroller class ie

//user vars
var email: String?
var givenName: String?
var familyName:String?
var phone: String?
var dob: NSDate?

In a method within that class i retrieve user data from coredata and set the user text fields with that data in a loop

for i in 0 ..< userTextFields.count {
   let field = userTextFields[i]
   let fieldName = userTextFieldKeyNames[i]
   let fieldText = currentUser.valueForKey(fieldName) as? String
   field.text = fieldText
 }

the fieldName variable in the loop matches the class's ivars above. Is there a way i can reference the ivars within the loop by matching it with the fieldName string so I can set the values of the ivars with the fetched coredata values ie in a literal sense saying something like the following ...

if self.property.name.text == fieldName {
  self.property.value == fieldText 
}

ie somehow resolving the various property names withing the class ... or is this bad design? .... if so any suggestions on achieving the same result in a better way





Aucun commentaire:

Enregistrer un commentaire