簡體   English   中英

如何快速遍歷NSDictionary

[英]how to iterate through an NSDictionary in order swift

是否可以按特定順序遍歷NSDictionary,以便我可以根據數據最初鍵入的順序在CoreData中保存鍵值對的索引? 即在下面的代碼中,集合1的索引將為1,集合2-2和集合3-3而不是隨機的,就像正常的NSDictionary行為一樣? 在此先感謝您是否可以提供解決方案,或者告訴我它不可能!

let string1 = "rain, wait, train".wordsInArray
let string2 = "oil, join, coin".wordsInArray
let string3 = "made, came, same".wordsInArray

let lists: [String: [String]] =
    ["Set 1: List 1": string1,
        "Set 1: List 2": string2,
        "Set 1: List 3": string3]

var index = 0

For list in lists {
 list.listIndex = index
 index = index + 1
 coreDataStack.saveMainContext() 
}

extension String {
    var wordsInArray:[String] {
        return componentsSeparatedByCharactersInSet(NSCharacterSet.punctuationCharacterSet()).joinWithSeparator("").componentsSeparatedByString(" ")
    }

在您的示例中,您的密鑰恰好以字母數字順序添加。 這可能是偶然的,但是如果您打算按鍵排序的順序獲取數據,則該請求與創建順序並不相同,並且很容易做到:

for (key,wordlist) in lists.sort({$0.0 < $1.0})
{
  // you will be getting the dictionary entries in key order
}

// trickier to access by index though
let aKey      = lists.keys.sort()[2]
let aWordList = lists[aKey]
// but it lets you get the wordlist from the key
let S1L3Words  = lists["Set 1: List 3"]

另一方面,如果您打算僅使用創建順序,並且不需要通過元素的鍵訪問元素,則可以將結構聲明為元組數組:

 let lists: [(String, [String])] =
            [
             ("Set 1: List 1", string1),
             ("Set 1: List 2", string2),
             ("Set 1: List 3", string3)
            ]

 // your for loop will get them in the same order

 for (key,wordlist) in lists 
 {
    // array order, no matter what the key values are
 }
 // also accessible directly by index
 let (aKey, aWordList) = lists[2] // ("Set 1: List 3", ["made", "came", "same"])

最后,如果您根本不需要鍵,則可以將其設置為數組數組:

 let lists: [[String]] = [ string1 , string2 , string3 ]
 for (key,wordlist) in lists 
 {
    // array order
 }
 // also accessible directly by index
 let aWordList = lists[2] // ["made", "came", "same"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM