I'm learning swift and trying to understand dictionaries. I'm used to PHP, where you might write the following...
$dataPoints = Array("A"=>1,"B"=>2,"C"=>3);
foreach($dataPoints as $value) {
echo($value);
}
In this example, the values would be output in order - 1, 2, 3
My swift code looks like this...
var dataPoints: Dictionary<String,Int> = ["A":1,"B":2,"C":3]
for (key, value) in dataPoints {
print(value)
}
However, the values come out in an unexpected order. Is there something clean I can do to keep the values in the order they were created, or can a swift dictionary never be sorted?
You can't sort a dictionary, it's an associative container. If you need a particular order, copy keys into an array, and sort them. Then iterate over the keys, and pull their corresponding values. @dasblinkenlight So can you tell me that how to sort an array in swift? @AleemAhmad Take a look at this answer, it has sortedKeys function.
Swift dictionary is an unordered collection of items. It stores elements in key/value pairs. Here, keys are unique identifiers that are associated with each value.
Initially, the value associated with the key 112 is "Kyle". Now, notice the line, Here, we have changed the value associated with the key 112 to "Stan". In Swift, we can access the keys and values of a dictionary independently. 1. Access Keys Only We use the keys property to access all the keys from the dictionary. For Example,
The result of sortedKeysAndValues is not a dictionary, it's an Array! For Swift 3, the following sort returnes sorted dictionary by keys:
As has already been answered, the point of a dictionary is that it is not sorted. There are three types of collections in Swift (and Objective-C)
An array is an ordered list of items. Use this when the order of the items is important.
A dictionary is an unordered collection of keys and values. Use this when you want to efficiently retrieve a value based on a key.
A set is a bag of unordered, unique items. Use this when you want to have a collection of unique items in no particular order.
For your case it seems that the ordering is what is important to you, but you want to store some kind of pair of values. Perhaps what you should be looking at is using an array of tuples:
something like this, maybe
let dataPoints = [("A", 1), ("B", 2), ("C", 3)]
for (letter, number) in dataPoints {
print("\(letter), \(number)")
}
which outputs
A, 1
B, 2
C, 3
Alternatively
If you don't know about the order of the items before their creation, but there is a natural ordering based on the keys, you could do something like this:
let dict = [
"A" : 1,
"B" : 2,
"C" : 3
]
for key in dict.keys.sort() {
guard let value = dict[key] else { break }
print("\(key), \(value)")
}
In this case you get an array of keys with their default sort order (you can use a different sort function if you have other requirements) and output the key values based on that sorted order.
From Apple docs:
Unlike items in an array, items in a dictionary do not have a specified order.
So, no, Swift dictionary are never "sorted". However, a quick Google search for "Swift ordered dictionary "will yield several implementation which may serve your needs:
For example:
https://github.com/lukaskubanek/OrderedDictionary
https://github.com/Marxon13/M13DataStructures/blob/master/Classes/OrderedDictionary.swift
Cocoapods could also help:
https://cocoapods.org/?q=ordered%20dict
You can now use the OrderedDictionary from the official Apple Collections library: https://github.com/apple/swift-collections
Just in case this is useful, based on the responses here and because I was receiving data from a JSON source, I decided the best approach was for me to convert my dictionary into a sorted array of tuples. I created the following function for this:
func dictionary_to_sorted_array(dict:Dictionary<String,Int>) ->Array<(key:String,value:Int)> {
var tuples: Array<(key:String,value:Int)> = Array()
let sortedKeys = (dict as NSDictionary).keysSortedByValueUsingSelector("compare:")
for key in sortedKeys {
tuples.append((key:key as! String,value:dict[key as! String]!))
}
return tuples
}
So then, I could use the following code:
var dataPoints: Dictionary<String,Int> = ["A":1,"B":2,"C":3]
dataPointsArray(dictionary_to_sorted_array(dataPoints))
for dataPoint in dataPointsArray {
print(dataPoint.value)
}
I'm very much a beginner with swift, so if anybody has a quicker way of doing this, that would be great!
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