How to set an attribute value where the attribute itself is variable in Swift

Viewed 320

I have a TableView with two columns - name and value where name is the attribute name itself for a class instance of an object from CoreData. And value is a textfield that is the value or that attribute and I want the user to be able to edit that in the tableview.

I have the property names and separately the values each stored in a separate array. So I have propertyArray and valueArray and the order of the arrays matches the keyed pairs.

So with that, I can certainly determine which property is being edited based upon the IndexPath, but I'm having trouble figuring out how to change the actual property value to what is newly entered in the text field.

The logic is I need :

animal.(propertyArray[IndexPath.row]) = textField.text

is there a way for me to create a string variable of "animal.whateverTheAttributeIs" and to somehow convert that into the left hand part of that equation?

1 Answers

You can have a dictionary that holds the mapping between row numbers and properties using KeyPath

struct Example {
    var id: String
    var name: String
    var text: String
}

let rowMap: [Int: WritableKeyPath<Test, String>] = [0: \.id, 1: \.name, 2: \.text]

and then you do a look up in the dictionary to get the right key path from a row

if let keypath = rowMap[indexPath.row] {
    exampleObject[keyPath: keypath] = "some value"
}

or for an NSObject subclass (that your class is) you can use setValue:forKeyPath as mentioned in the comments

if let keypath = rowMap[indexPath.row] {
    exampleObject.setValue("some value", forKeyPath: keypath)
}

This is somewhat simplified since I assume from your examples that all properties are of type String

Related