Search code examples
iosswiftnsdictionaryclass-attributes

How to access a variable using its name as a string


I was thinking of using a plist file to configure how I would upload a form to my server but then I realised I don't know how I could do one crucial part of this or even if this is possible since you can't dynamically declare variables with swift.

Basically I was thinking of using a dictionary like this

form:

  • property_name: backend_name

and then in my form upload method I would do something that would look like this

formValues: [String:String] = [:]
form.forEach { (property_name, backend_name) in
  let value = someController[property_name] // to do the equivalent of someController.property_name
  formValues[backend_name] = value
}
// ...
formValues.forEach { (backend_name, value) in
  multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: backend_name)
}

the problem is I don't know how to this part

let value = someController[property_name]

Solution

  • The problem you're trying to solve is serializing your data for a server. I don't know whether the approach you're trying is possible in Swift, but it's definitely not the right one. If you're using Swift 4, you could create Codable model objects, so this serialization will be all under the hood. Otherwise, you'll most likely need to create this [String: Any] manually.

    Using Codable to serialize/deserialize objects