在swift中使用有序形式在字典中迭代对象

时间:2015-05-29 03:33:26

标签: swift nsdictionary nsmutabledictionary ios8.1

我有一个字典我想以有序的形式迭代它,因为对象在字典中,但在迭代之后它以随机顺序迭代。请帮忙 提前谢谢。

1 个答案:

答案 0 :(得分:1)

您无法对字典进行排序,但您可以按如下方式对其键进行排序:

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)")
}