Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
]

println(dict)

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?

like image 645
TruMan1 Avatar asked Apr 09 '15 13:04

TruMan1


Video Answer


3 Answers

Swift 5.1:

Use a KeyValuePairs instance when you need an ordered collection of key-value pairs and don’t require the fast key lookup that the Dictionary type provides.

You initialize a KeyValuePairs instance using a Swift dictionary literal. Besides maintaining the order of the original dictionary literal, KeyValuePairs also allows duplicates keys. For example:

let recordTimes: KeyValuePairs = ["Florence Griffith-Joyner": 10.49,
                                  "Evelyn Ashford": 10.76,
                                  "Evelyn Ashford": 10.79,
                                  "Marlies Gohr": 10.81]

print(recordTimes.first!)
// Prints "("Florence Griffith-Joyner", 10.49)"
like image 57
Carlos Chaguendo Avatar answered Oct 19 '22 02:10

Carlos Chaguendo


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 :)

like image 28
Martin R Avatar answered Oct 19 '22 03:10

Martin R


As Apple says:

Dictionaries are unordered collections of key-value associations.

Link: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html

Don't know if that will help you but in this link there is an implementation of an ordereddictionary: http://www.raywenderlich.com/82572/swift-generics-tutorial

like image 5
Javier Flores Font Avatar answered Oct 19 '22 01:10

Javier Flores Font