2017-02-24 63 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