WilliamCarter
WilliamCarter

Reputation: 25

Sort Dictionary By Date Value- Swift

So I need to be able to sort my dictionary from the value "date" (newest to oldest)

The way my dictionary is formatted is that there are multiple people with the values: date(creationdate), name and, email. The array(peoples):

let bob =   ["name": "Bob", "date": Date(timeIntervalSince1970: 1594756208.777499), "email": "[email protected]"] as [String : Any]
let steve = ["name": "Steve", "date": Date(timeIntervalSince1970: 1604756208.777499), "email": "[email protected]"] as [String : Any]
let sammy = ["name": "Sammy", "date": Date(timeIntervalSince1970: 1594756210.778510), "email": "[email protected]"] as [String : Any]
let peoples = [bob, steve, sammy}

With this array I tried to sort it like this:

let peoplesSorted = peoples.sorted(by: { 0$.date > 1$.date })

But it doesn't work and gives the error "Binary operator '>' cannot be applied to two 'Date?' operands"

I also tried formatting the date into a string (yyyy/MM/dd HH:mm:ss) but I couldn't figure out the code in the sorted() function.

Thanks for the help!

Upvotes: 0

Views: 220

Answers (2)

Duncan C
Duncan C

Reputation: 131481

As vadian said, you have a dictionary of type [String: Any]. You can't use dot notation on dictionaries, and you also can't compare objects of type Any.

Taking vadian's suggestion, your code is cleaner if you refactor your dictionary as a struct:

struct Person {
    let name: String
    let date: Date
    let email: String
}

let bob = Person(name: "Bob", date: Date(timeIntervalSince1970: 1594756208.777499), email: "[email protected]")
let steve = Person(name: "Steve", date: Date(timeIntervalSince1970: 1604756208.777499), email: "[email protected]")
let sammy = Person(name: "Sammy", date: Date(timeIntervalSince1970: 1594756210.778510), email: "[email protected]" )


let peoples = [bob, steve, sammy]

let peoplesSorted = peoples.sorted {
    return $0.date > $1.date }

peoplesSorted.forEach {
    print($0)
}

Upvotes: 1

vadian
vadian

Reputation: 285200

The error message doesn't match the code. Apart from the typos you should get

Ambiguous use of operator '>'

Any is the don't care type but the compiler must know the static type when applying operators.

And standard dictionaries don't support dot notation

let peoplesSorted = peoples.sorted(by: { ($0["date"] as! Date) > $1["date"] as! Date })

A better type is a custom struct which supports dot notation and strong types.

Upvotes: 1

Related Questions