TruMan1 TruMan1 - 1 year ago 210
Swift Question

Preserve order of dictionary items as declared in Swift?

When creating a key/value dictionary, it is returned as randomly sorted. I was hoping that they would be in the same order as it was created.

For example, see this code:

var dict = [
"kg": 1,
"g": 2,
"mg": 3,
"lb": 4,
"oz": 5,
"t": 6


This returns the following:

[kg: 1, oz: 5, g: 2, mg: 3, lb: 4, t: 6]

How do I preserve the order in which the dictionary was declared?

Answer Source

In your case an array of custom objects might be more appropriate. Here is a simple example that should help to get you started:

struct Unit : Printable {
    let name: String
    let factor: Double

    // println() should print just the unit name:
    var description: String { return name }

let units = [
    Unit(name: "kg", factor: 1000.0),
    Unit(name: "g", factor: 1.0),
    Unit(name: "mg", factor: 0.001),
    Unit(name: "lb", factor: 453.592292),
    Unit(name: "oz", factor: 28.349523)

println(units) // [kg, g, mg, lb, oz]

(I am not sure if the non-metric unit factors are correct :)