Albert Ghar Albert Ghar - 4 months ago 7
Swift Question

Sorting array of dictionaries of strings in Swift

I'm trying to sort an array of dictionaries in Swift. My structure is like this:

[
[
"DateTime": "8/16/16, 4:00 PM",
"Owner": "Teacher1",
"Subject": "AP Euro",
"Address": "Mr. Hughes\' Room",
"Type": "Final",
"Timestamp": "2016081616009498",
"Location": "On Campus",
"Duration": "50 min",
"Members": "ownerKey,1,107434,109431"
],
[
"DateTime": "7/29/16, 6:35 AM",
"Owner": "109431",
"Subject": "Algebra 2 Acc",
"Address": "Library",
"Type": "Quiz",
"Timestamp": "2016072906356642",
"Location": "On Campus",
"Duration": "5 min",
"Members": "ownerKey"
]
]


I'm trying to sort the array by each "
Timestamp
" value in each dictionary. How can I do this?

My current code (not working) is:

self.todayArray.sortInPlace {item1,item2 in

let date1 = Int("\(item1["Timestamp"])")
let date2 = Int("\(item2["Timestamp"])")

return date1 > date2
}

Answer

N/M all the stuff below, it's to sort by the DateTime field, you're trying to sort on the Timestamp field which is already lexicographically sorted, so just use:

foo.sortInPlace { $0["Timestamp"] < $1["Timestamp"] }

Since timestamp is an string-encoded date, you'll need to convert it to something more useful first, using an NSDateFormatter is the easiest way:

There's a lot of ! in here that you should do something more appropriate with, but this gives you the basic idea:

let foo = [
    [
        "DateTime": "8/16/16, 4:00 PM",
        "Owner": "Teacher1",
        "Subject": "AP Euro",
        "Address": "Mr. Hughes\' Room",
        "Type": "Final",
        "Timestamp": "2016081616009498",
        "Location": "On Campus",
        "Duration": "50 min",
        "Members": "ownerKey,1,107434,109431"
    ],
    [
        "DateTime": "7/29/16, 6:35 AM",
        "Owner": "109431",
        "Subject": "Algebra 2 Acc",
        "Address": "Library",
        "Type": "Quiz",
        "Timestamp": "2016072906356642",
        "Location": "On Campus",
        "Duration": "5 min",
        "Members": "ownerKey"
    ]
]

let formatter = NSDateFormatter()
formatter.dateFormat = "M/dd/yy, h:mm a"

let sorted = foo.sort {
    formatter.dateFromString($0["DateTime"]!)!.compare(formatter.dateFromString($1["DateTime"]!)!) != .OrderedDescending
}
print("\(sorted)")
Comments