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?
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)"
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 :)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With