Dictionary won't sort (Xcode 9.2)

I don't have much experience with Xcode and Swift, and I've had quite a number of issues; but this one left me puzzled.


For a task in class, we had to sort a dictionary by its values. I was successful with the sorting part, but it seems the sorted keysand values won't load back into the dictionary in the correct order.

let numberOfPositions = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]


print("\nCaptain | Gpa\n")


for position in numberOfPositions {

captainGPAs[names[position]] = gpas[position]

print("\(names[position]) | \(gpas[position])")

}


Here's a snippet of what I did (I set the keys and values into separate arrays for sorting then loaded them back in). Now, I know it's sorted because of the printing part of the loop.

Captain | Gpa

Young, Everett | 1.8

Kirk, James | 1.9

Reynolds, Malcolm | 2.1

Lin, Portia | 2.1

Lorca, Gabriel | 2.2

May, Melinda | 2.5

Hernandez, Erika | 2.8

Adama, William | 2.8

Archer, Jonathan | 3.1

Sisko, Benjamin | 3.5

Georgiou, Philippa | 3.7

Janeway, Kathryn | 3.9

Picard, JeanLuc | 4.0

Carter, Samantha | 4.0

But when I print or call the captainGPAs, it's in its original order despite it being empty before the sort.


["Kirk, James": 1.8999999999999999, "Hernandez, Erika": 2.7999999999999998, "May, Melinda": 2.5, "Reynolds, Malcolm": 2.1000000000000001, "Lorca, Gabriel": 2.2000000000000002, "Picard, JeanLuc": 4.0, "Janeway, Kathryn": 3.8999999999999999, "Sisko, Benjamin": 3.5, "Georgiou, Philippa": 3.7000000000000002, "Young, Everett": 1.8, "Archer, Jonathan": 3.1000000000000001, "Carter, Samantha": 4.0, "Lin, Portia": 2.1000000000000001, "Adama, William": 2.7999999999999998]


If you have a solution to this issue, it would be greatly appreciated.


(Content of images pasted)

Accepted Reply

Hello Tenma,

You can't sort a dictionary. You can extract values and store them, sorted, into an array. But if you put them back into an associative container, they will be un-sorted again.

Replies

>I added images that don't seem to be showing


Note you can add images, but others are prohibited from viewing them. As an alternative, use your words, or...upload them to a server, add the urls to a comment and be sure to break the urls to avoid waiting for moderation.


Example: h ttp://www.ebay.com

Hello Tenma,

You can't sort a dictionary. You can extract values and store them, sorted, into an array. But if you put them back into an associative container, they will be un-sorted again.