0

I have a message array. Each message has a timestamp property that's an Int. I'm trying to sort out the array based on the most recent date, but I'm getting an error saying:

Value of type 'Int' has no member 'intValue'

self.messages.sort(by: { (message1, message2) -> Bool in
     return message1.timestamp!.intValue > message2.timestamp!.intValue
})
Dani
  • 3,427
  • 3
  • 28
  • 54
  • 1
    `return message1.timestamp! > message2.timestamp!` make sure timestamp it is not nil – Leo Dabus Aug 26 '18 at 17:42
  • @LeoDabus oh, yeah. That's right. This works. Please, add it as an answer so I can accept it. Thank you – Dani Aug 26 '18 at 17:44
  • you are welcome – Leo Dabus Aug 26 '18 at 17:46
  • Possible duplicate of [Swift how to sort array of custom objects by property value](https://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value) – regina_fallangi Aug 26 '18 at 17:50
  • 2
    Side note: Can a message lack the timestamp? If not, make `timestamp` non-optional. – vadian Aug 26 '18 at 17:50
  • @vadian it is an optional, but I know it always has a value. I just tried to sort it the wrong way. Thank you for your time though. I appreciate it. – Dani Aug 26 '18 at 17:56
  • 2
    If you *know it always has a value* make it non-optional. Non-optionals cannot crash. – vadian Aug 26 '18 at 17:59

1 Answers1

2

The error message it is pretty self explanatory timestamp it is not a NSNumber it is an Int therefore you can compare them directly. If you are sure the timestamp will never be nil it is better change its declaration to non-optional:

messages.sort { $0.timestamp > $1.timestamp }
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571