2017-02-24 62 views
2

我在plist中有一些重复的数据,然后将其提取到字典中并显示在我的应用程序中。唯一的问题是,它需要按照与plist相同的顺序,但很明显,字典不能被排序,并且它是未排序的。那么,我将如何实现这一目标?排序plist数据

我的plist数据重复这样

enter image description here

我再转化[Int : ItemType]类型的字典,ItemType的是我的数据协议,如:

class ExhibitionUnarchiver { 
    class func exhibitionsFromDictionary(_ dictionary: [String: AnyObject]) throws -> [Int : ItemType] { 
     var inventory: [Int : ItemType] = [:] 
     var i = 0; 

     print(dictionary) 

     for (key, value) in dictionary { 
      if let itemDict = value as? [String : String], 
      let title = itemDict["title"], 
      let audio = itemDict["audio"], 
      let image = itemDict["image"], 
      let description = itemDict["description"]{ 
       let item = ExhibitionItem(title: title, image: image, audio: audio, description: description) 
       inventory.updateValue(item, forKey: i); 
       i += 1; 
      } 
     } 

     return inventory 
    } 
} 

这会导致这样的字典:

[12: App.ExhibitionItem(title: "Water Bonsai", image: "waterbonsai.jpg", audio: "exhibit-audio-1", description: "blah blah blah"), 17: App.ExhibitionItem..... 

我希望,因为我做了关键的诠释我可以分类,但到目前为止,我没有运气。你可能会告诉我很快就会发现,所以请提供你认为相关的任何信息。谢谢!

+0

我想维持顺序的唯一方法是使用数组而不是dictio进制。如果字典中的“Int”键很重要,我会将它作为“title”旁边的同级存储。 –

+0

将代码中的数组转换为字典很容易,但在字典中维护顺序是不可能的。 –

+0

我一直在想......但是因为它是'ExhibitionItem'结构的一部分,我不能像普通数组那样排序吗? –

回答

1

词典没有排序。如果你需要一个特定的顺序,使Array类型的root

enter image description here


或由键手动对其进行排序:

var root = [Int:[String:String]]() 
root[1] = ["title":"Hi"] 
root[2] = ["title":"Ho"] 

let result = root.sorted { $0.0 < $1.0 } 

print(result) 

打印:

[(1, ["title": "Hi"]), (2, ["title": "Ho"])] 
+0

如果根是一个数组,我将如何按键排序,例如“Item 0”,“Item 1”等 –

+0

@ShanRobertson数组从索引0到索引count-1排序。它已经*按你想要的顺序排列。 – Hamish

+1

正确。枚举键将被废弃。也给答案添加了排序示例。 – shallowThought