Ordered map in Swift

"If you need an ordered collection of key-value pairs and don’t need the fast key lookup that Dictionary provides, see the DictionaryLiteral type for an alternative." - https://developer.apple.com/reference/swift/dictionary


Just use an array of tuples instead. Sort by whatever you like. All "built-in".

var array = [(name: String, value: String)]()
// add elements
array.sort() { $0.name < $1.name }
// or
array.sort() { $0.0 < $1.0 }

You can use KeyValuePairs, from documentation:

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.

let pairs: KeyValuePairs = ["john": 1,"ben": 2,"bob": 3,"hans": 4]
print(pairs.first!)

//prints (key: "john", value: 1)


You can order them by having keys with type Int.

var myDictionary: [Int: [String: String]]?

or

var myDictionary: [Int: (String, String)]?

I recommend the first one since it is a more common format (JSON for example).