简体   繁体   中英

Swift dictionary sorting

just wondered how dictionary sorts in Swift. eg the following code.

var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic"]

occupations["Jayne"] = "Pirate"

for (name, occupation) in occupations{
print("\(name) is a \(occupation)")
}

The outcome looks like this

Kaylee is a Mechanic 
Malcolm is a Captain
Jayne is a Pirate

My question stands. How does the cycle decide which name(or a key) will be first passed through the above cycle?

From Apple Collection Types Documentation :

A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order .

By default, dictionary data structure has unspecified ordering, means that each time you will iterate through it you might have a different sorting. However you can sort based on the keys or the values of it, both of them are represented as arrays.

So, let's say that you want to sort based on the keys:

    var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic"]

occupations["Jayne"] = "Pirate"

for key in occupations.keys.sort() {
    print("KEY: \(key) VALUE: \(occupations[key])")
}

Console should shows -sorted based on the key-:

KEY : Jayne VALUE : Optional("Pirate")

KEY : Kaylee VALUE : Optional("Mechanic")

KEY : Malcolm VALUE : Optional("Captain")

Note that the values are optionals, you may need to "optional binding" them...

Hope this helped.

I think you are looking for something like this:

    var occupations = [
        "Malcolm": "Captain",
        "Kaylee": "Mechanic"]

    occupations["Jayne"] = "Pirate"

    let unsortedKeys = occupations.keys //get dictionary keys
    let sortedKeys = unsortedKeys.sorted(by: <) //sort dictionary keys
    for key in sortedKeys {
        print("\(key) is a \(occupations[key])")
    }

Hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM