Max Max - 5 months ago 16x
Swift Question

Converting my code to new Swift (2.2), dictionary doesn't have array function?

I'm trying to convert my code to Swift 2.2 (I haven't opened this code since before Swift 2.0 was released). One of the things I've done a lot of is converting dictionarys to arrays using the .array function of dictionary items. This is apparently not a function anymore. What am I supposed to do? I thought the .elements function would work but I can't pull using an array [index] command.


Rob Rob

There are many ways to accomplish something like this. The easiest way is to change your model to be an array of dictionaries (or of custom objects):

var people = [
    ["name": "Rob", "city": "New York", "state": "NY", "street": "11 Wall Street"],
    ["name": "Jim", "city": "Washington", "state": "DC", "street": "1600 Pennsylvania Avenue"],
    ["name": "Sue", "city": "Los Angeles", "state": "CA", "street": "4059 Mt Lee Dr."]

And, if you want to sort that by name:

people.sortInPlace { return $0["name"] < $1["name"] }

Or, let's imagine that you really have a dictionary where a unique identifier is the key:

var people = [
    34: ["name": "Rob", "city": "New York", "state": "NY", "street": "11 Wall Street"],
    42: ["name": "Jim", "city": "Washington", "state": "DC", "street": "1600 Pennsylvania Avenue"],
    65: ["name": "Sue", "city": "Los Angeles", "state": "CA", "street": "4059 Mt Lee Dr."]

You can then build an array of identifiers sorted by name:

let sortedIdentifiers = { return ($0, $1["name"]) }  // this builds array of items like `(34, "Rob")`
    .sort { $0.1 < $1.1 }                                       // this sorts that array by the second item (e.g. the name)
    .map { $0.0 }                                               // just return the identifiers sorted by name

You can now subscript the sortedIdentifiers, e.g.:


There are lots of ways to tackle this. If you edit your question to show us what your model looks like, we might be able to offer more specific solutions.