Swift: Sorted Dictionary

I quickly learn and try to understand dictionaries. I'm used to PHP where you can write the following ...

$dataPoints = Array("A"=>1,"B"=>2,"C"=>3);
foreach($dataPoints as $value) {
    echo($value);
}

In this example, the values ​​will be displayed in the order - 1, 2, 3

My quick 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 unexpected order. Is there anything clean that I can do to save the values ​​in the order in which they were created, or will the quick dictionary never be sorted?

+5
source share
4 answers

As already mentioned, the point of the 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 elements. Use this when the order of the elements is important.

- . , .

- , . , .

, - , , - . , :

- ,

let dataPoints = [("A", 1), ("B", 2), ("C", 3)]

for (letter, number) in dataPoints {
    print("\(letter), \(number)")
}

A, 1
B, 2
C, 3

, , - :

let dict = [
    "A" : 1,
    "B" : 2,
    "C" : 3
]

for key in dict.keys.sort() {
    guard let value = dict[key] else { break }
    print("\(key), \(value)")
}

( , ) .

+7

, , JSON, , . :

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
}

, :

var dataPoints: Dictionary<String,Int> = ["A":1,"B":2,"C":3]
dataPointsArray(dictionary_to_sorted_array(dataPoints))
for dataPoint in dataPointsArray {
    print(dataPoint.value)
}

, , - , !

0

Swift 4 sorted(by:) (). :

var dataPoints = ["A":1,"B":2,"C":3]

var sortedDataPoints = dataPoints.sorted(by: { $0.value < $1.value })
// [(key: "A", value: 1), (key: "B", value: 2), (key: "C", value: 3)]

for (_, value) in sortedDataPoints {
    print(value)
}
0

Source: https://habr.com/ru/post/1617966/


All Articles