Michael Voccola Michael Voccola - 9 months ago 17
Swift Question

Should a dictionary be converted to a class or struct in Swift?

I am working on a native iOS application that receives data in JSON format from a web-service which we are also in control of. The plan is to change out the backend database in a bout 18 months in favor of a different platform.

With that in mind, we want to be sure that that iOS app is going to be relatively easy to adapt to the new datasource, particularly as we may change the keys used in the associative array received from the server via JSON.

There are two goals:

  1. Create a single location for each PHP request where the keys can be modified if needed. This would avoid digging through code to find things like

  2. Clean up our existing code to also eliminate references like

We are both very new to Swift with no Objective-C experience, but I am was thinking a Struct or Class would be appropriate to create references like

Should a dictionary be converted into a class or struct? Sample code representing a reusable method of taking a
Dictionary<String, String>
as shown below and converting it to the recommended type would be extremely helpful.

Example Dictionary:

job = {
"jobNumber" : "1234",
"jobName" : "Awards Ceremony",
"client" : "ACME Productions"

Desired result:

println("job name is \(job.name)")
// prints: job name is Awards Ceremony


To access it like this you need to convert your dictionary to Struct as follow:

let jobsDictionary = [
    "jobNumber" : "1234",
    "jobName" : "Awards Ceremony",
    "client" : "ACME Productions"

struct Job {
    var number = 0
    var name = ""
    var client = ""
    var description: String {
        return "Job#: " + number.description + " - name: " + name + " - client: " + client

let job = Job(number:  (jobsDictionary["jobNumber"]! as NSString).integerValue, name: jobsDictionary["jobName"]!, client: jobsDictionary["client"]!)

println(job.number)       //  1234
println(job.name)         //  "Awards Ceremony"
println(job.client)       //  "ACME Productions"
println(job.description)  //  "Job#: 1234 - name: Awards Ceremony - client: ACME Productions"