I have a dictionary i want to iterate it in ordered form as the objects are in the dictionary, but after iterating it is iterating in random order. Please help Thanks in advance.
Asked
Active
Viewed 155 times
-1
-
1"i want to iterate it in ordered form as the objects are in the dictionary" Meaningless. A dictionary has _no order_. – matt May 29 '15 at 04:07
-
You have to implement custom dictionary type. – rintaro May 29 '15 at 04:59
1 Answers
1
You can't sort a dictionary but you can sort its keys as follow:
let myDict: [String:String] = ["car":"blue", "watch":"black", "bike": "red"]
for key in myDict.keys.array.sorted(<) {
let value = myDict[key]!
println("\(key) = \(value)")
}
let dashboardItemsTuples : [(String , String)] = [("All Cards" , "cards" ), ("Cards by Topic" , "cards_topic"), ("Lessons" , "lesson" ), ("Audio" , "audio"), ("Video" ,"video") ,( "Ebook" , "ebook") , ("Bookmarked Cards" , "bookmark_cards" ), ("Upgrade","upgrade") , ("Downloads" ,"downloads")]
for (key,value) in dashboardItemsTuples {
println("\(key)=\(value)")
}

Leo Dabus
- 229,809
- 59
- 489
- 571
-
Thanks but this is sorting alphabetically not as my dictionary generated. – Gopal Devra May 29 '15 at 03:48
-
-
Could you tell me how to take object as they are inserted into the dictionary. – Gopal Devra May 29 '15 at 03:48
-
-
let dashboardItems : [String : String] = ["All Cards" : "cards" , "Cards by Topic": "cards_topic", "Lessons": "lesson" , "Audio":"audio", "Video" :"video" , "Ebook": "ebook" , "Bookmarked Cards" :"bookmark_cards" , "Upgrade":"upgrade" , "Downloads" :"downloads"] – Gopal Devra May 29 '15 at 03:49
-
-
1An Array would keep the order you insert the items a Dictionary won't – Leo Dabus May 29 '15 at 03:56
-
-
or you can create an array to use as index. Everytime you add a key value to your dictionary you add the key to your index array – Leo Dabus May 29 '15 at 04:06