swiftforced-unwrapping

How can I avoide Forced unwarapping in this?


How can I avoid forced unwrapping in below code?

 self.array = self.array.sorted(by: { Date(timeIntervalSince1970: ($0?.event?.dateRecorded)!) > Date(timeIntervalSince1970: ($1?.event?.dateRecorded)!) })

Solution

  • Use nil-coalescing to replace a nil timestamp with some default value, e.g. a timestamp far far in the past:

    let past = -TimeInterval.greatestFiniteMagnitude
    self.array.sort(by: { 
         $0.event?.dateRecorded ?? past > $1.event?.dateRecorded ?? past
    })
    

    As mentioned above, there is no need to compare the timestamps to Date values, the numeric timestamps can be compared directly.