PJR
PJR

Reputation: 13180

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)!) })

Upvotes: 0

Views: 54

Answers (1)

Martin R
Martin R

Reputation: 540055

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.

Upvotes: 3

Related Questions