Sortuj Słownik według kluczy

Chcę posortować słownik w języku Swift. Mam taki słownik:

"A" => Array[]
"Z" => Array[]
"D" => Array[]

Itd. I want it to be like

"A" => Array[]
"D" => Array[]
"Z" => Array[]

Itd.

Próbowałem wielu rozwiązań na tak, ale nikt nie pracował dla mnie. Używam Xcode6 Beta 5 i na nim niektóre dają błąd kompilatora, a niektóre rozwiązania dają wyjątki. Więc każdy, kto może opublikować roboczą kopię sortowania słownika.

Author: Dan Beaulieu, 2014-08-19

10 answers

let dictionary = [
    "A" : [1, 2],
    "Z" : [3, 4],
    "D" : [5, 6]
]

let sortedKeys = Array(dictionary.keys).sorted(<) // ["A", "D", "Z"]

EDIT:

Posortowana tablica z powyższego kodu zawiera tylko klucze, podczas gdy wartości muszą być pobrane z oryginalnego słownika. Jednak 'Dictionary' jest również 'CollectionType' par (klucz, wartość) i możemy użyć funkcji global 'sorted', aby uzyskać posortowaną tablicę zawierającą zarówno klucze, jak i wartości, tak:

let sortedKeysAndValues = sorted(dictionary) { $0.0 < $1.0 }
println(sortedKeysAndValues) // [(A, [1, 2]), (D, [5, 6]), (Z, [3, 4])]

EDIT2: miesięczna zmiana składni Swift obecnie preferuje

let sortedKeys = Array(dictionary.keys).sort(<) // ["A", "D", "Z"]

Globalny sorted jest przestarzały.

 127
Author: Ivica M.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-31 18:10:21

Swift 2.0

Zaktualizowana Wersja odpowiedzi Ivica M:

let wordDict = [
     "A" : [1, 2],
     "Z" : [3, 4],
     "D" : [5, 6]
]

let sortedDict = wordDict.sort { $0.0 < $1.0 }
print("\(sortedDict)") // 

Swift 3

wordDict.sorted(by: { $0.0 < $1.0 })

Notice:

Niektórzy z was wydają się zaskoczeni, że wynikowa tablica nie jest słownikiem. słowniki nie mogą być sortowane! Wynikowy typ danych to posortowana tablica, tak jak w odpowiedzi @Ivica.

 81
Author: Dan Beaulieu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-27 12:26:41

Jeśli chcesz iterować zarówno klucze, jak i wartości w uporządkowanej kolejności kluczy, ten formularz jest dość zwięzły

let d = [
    "A" : [1, 2],
    "Z" : [3, 4],
    "D" : [5, 6]
]

for (k,v) in Array(d).sorted({$0.0 < $1.0}) {
    println("\(k):\(v)")
}
 25
Author: rks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-07 15:50:40

W swift 4 możesz napisać to mądrzej:

let d = [ 1 : "hello", 2 : "bye", -1 : "foo" ]
d = [Int : String](uniqueKeysWithValues: d.sorted{ $0.key < $1.key })
 7
Author: Davide Gianessi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-12 14:28:15

Dla Swifta 4 działa mi:

let dicNumArray = ["q":[1,2,3,4,5],"a":[2,3,4,5,5],"s":[123,123,132,43,4],"t":[00,88,66,542,321]]

let sortedDic = dicNumArray.sorted { (aDic, bDic) -> Bool in
    return aDic.key < bDic.key
}
 4
Author: Shiv Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-18 11:51:26

W systemie iOS 9 i xcode 7.3 swift 2.2 jest niemożliwy, Zmień "posortowane" NA "Sortuj", tak:

let dictionary = ["main course": 10.99, "dessert": 2.99, "salad": 5.99]
let sortedKeysAndValues = Array(dictionary).sort({ $0.0 < $1.0 })
print(sortedKeysAndValues)

//sortedKeysAndValues = ["desert": 2.99, "main course": 10.99, "salad": 5.99]
 3
Author: AmyNguyen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-03 03:04:30

Dla Swift 3, następujące sortowanie zwraca posortowany słownik według kluczy:

let unsortedDictionary = ["4": "four", "2": "two", "1": "one", "3": "three"]

let sortedDictionary = unsortedDictionary.sorted(by: { $0.0.key < $0.1.key })

print(sortedDictionary)
// ["1": "one", "2": "two", "3": "three", "4": "four"]
 3
Author: Arijan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-29 10:02:46

Próbowałem wszystkich powyższych, w skrócie wszystko czego potrzebujesz to

let sorted = dictionary.sorted { $0.key < $1.key }
let keysArraySorted = Array(sorted.map({ $0.key }))
let valuesArraySorted = Array(sorted.map({ $0.value }))
 3
Author: Elsammak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-29 05:24:18

Dla Swifta 3 u mnie zadziałało a składnia Swifta 2 nie działa:

// menu is a dictionary in this example

var menu = ["main course": 10.99, "dessert": 2.99, "salad": 5.99]

let sortedDict = menu.sorted(by: <)

// without "by:" it does not work in Swift 3
 1
Author: Joeri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-16 05:07:57

Swift 3 jest sortowany (według:

let dictionary = [
    "A" : [1, 2],
    "Z" : [3, 4],
    "D" : [5, 6]
]

let sortedKeys = Array(dictionary.keys).sorted(by:<) // ["A", "D", "Z"]
 1
Author: Shadros,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-20 06:27:25