【问题标题】:how to iterate through an NSDictionary in order swift如何快速遍历 NSDictionary
【发布时间】:2016-01-15 14:45:35
【问题描述】:

是否可以按特定顺序遍历 NSDictionary,以便我可以根据最初键入数据的顺序在 CoreData 中保存键值对的索引?即在下面的代码中,Set 1 的索引为 1、set 2 - 2 和 set 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(" ")
    }

【问题讨论】:

  • 字典是一个无序的集合。无法保证事情会保持相同的顺序,并且您派生的任何索引都可能不指向同一项目。如果你想保持秩序,最好使用数组。
  • 绝对有可能,因为您已经定义了顺序,您唯一要做的就是将其保存在任何已订购的集合中并随意使用。当然,保持两个集合同步也很重要,这很容易出错,因此您可能需要重新考虑数据结构,并将现在的键作为对象的简单属性存储在单个有序集合中。
  • ... 但是字典有唯一的键,所以你可以只记住字典中的键,而不是记住索引。并且内置的迭代器会给你键值对,所以很容易记住你感兴趣的一个键。
  • 嗨@A-Live - 我如何将其保存为有序集合?

标签: swift nsdictionary


【解决方案1】:

在您的示例中,您的密钥恰好按字母数字顺序添加。这可能是偶然的,但如果您打算按键排序顺序获取数据,这与创建顺序不同,而且很容易做到:

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"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 2017-05-08
    • 2013-04-07
    • 2015-08-16
    • 1970-01-01
    • 2015-04-20
    相关资源
    最近更新 更多