casillas
casillas

Reputation: 16813

How to sort timestamps in the dictionary object

I am trying to write a LRU cache and creates an object and check which item is added first by looking at the timestamps as follows.

import Foundation

class Item : Comparable 
{
    var timeStamp : Date
    var value : Int

    init(_ value: Int)
    {
      self.value = value
      self.timeStamp = Date()
    }
}

func < (lhs: Item, rhs: Item) -> Bool {
    return lhs.timeStamp < rhs.timeStamp
}

func == (lhs: Item, rhs: Item) -> Bool {
    return lhs.timeStamp == rhs.timeStamp
}

var item1 = Item (1)
var item2 = Item (2)
var item3 = Item (3)

var items = [1: item1 , 2 : item2, 3: item3]
items = items.sorted(by: {$0.date.compare($1.date) == .orderedDescending})
print(items)

I am getting the following issue:

error: value of tuple type '(key: Int, value: Item)' has no member 'date' items = items.sorted(by: {$0.date.compare($1.date) == .orderedDescending})

Then I need to sort and find the earliest timestamps in the dictionary.

Upvotes: 1

Views: 139

Answers (2)

David Pasztor
David Pasztor

Reputation: 54755

You can simply use the < operator to compare Dates.

let sortedItems = items.sorted(by: {$0.value.timeStamp < $1.value.timeStamp})

I wouldn't recommend implementing Comparable, since even though my might want to sort your items based on simply their timestamps in some scenarios, it seems like you should take into consideration the value as well, especially for equality checking in other scenarios.

If you really only need to check timeStamp for comparison, you can make Item conform to Comparable and shorten your closure for sorted.

extension Item: Comparable {
    static func == (lhs: Item, rhs: Item) -> Bool {
        return lhs.timeStamp == rhs.timeStamp
    }

    static func < (lhs: Item, rhs: Item) -> Bool {
        return lhs.timeStamp < rhs.timeStamp
    }
}

let sortedItems = items.sorted(by: {$0.value < $1.value})

Upvotes: 2

Vyacheslav
Vyacheslav

Reputation: 27221

Just implement Comparable protocol for Item, or, maybe more useful [1: Item(1),2: Item(2),2: Item(3),].sorted { $0.value.timeStamp < $1.value.timeStamp }

Upvotes: 2

Related Questions