I am using a dictionary to store key-value pairs. It's storing correctly kay-value pair. But when I try to retrieve all keys and all values separately, it's printing different differently.
Here is the example,
var sampleDic:[String:Any] = [:]
sampleDic["one"] = 1
sampleDic["two"] = 2
sampleDic["three"] = 3
print("keys: \(sampleDic.keys)")
print("Values: \(sampleDic.values)")
sometimes its prints,
keys: ["one", "two", "three"]
Values: [1, 2, 3]
and sometimes its prints,
keys: ["three", "one", "two"]
Values: [3, 1, 2]
each time, whenever I run the code, I will get different output.
How I can get the output in the same sequence for keys and values always. Both keys and values must be printed in array bases on which key/value they stored in the dictionary.
If this is not possible with dictionaries, then is there an alternative way to store and get values like this?
Dictionaries stores mappings between keys and values, not a list of key value pairs, so there is no order.
If you want an order, you can give it one by sorting the key value pairs, e.g. by the keys
This produces a
[(String, Any)]. If you actually want a[String]and a[Any], you can write anunzipfunction (from answer by Rob):Now you can do: