Shan Robertson Shan Robertson -4 years ago 141
Swift Question

Sorting plist data

I've got some repeating data in a plist, I then extract it into a dictionary and display it in my app. The only problem is that it needs to be in the same order i put it in the plist, but obviously, dictionary's can't be sorted and it comes out unsorted. So how would i achieve this?

My plist data repeats like this

enter image description here

I then convert that into a dictionary of type

[Int : ItemType]
, ItemType is my data protocol, like this:

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


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

Which results in a dictionary like this:

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

I was hoping that since i made the key's Int's i could sort it but so far i'm having no luck. You might be able to tell i'm fairly new to swift, so please provide any info you think would be relevant. Thanks!

Answer Source

A Dictionary has no order. If you need a specific order, make root of type Array:

enter image description here

or sort it by the key manually:

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

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



[(1, ["title": "Hi"]), (2, ["title": "Ho"])]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download