Array sorting error: “ Binary operator '<&#

2020-05-02 02:30发布

问题:

This is the code for sorting an array by the each cells in the tableView's timestamp.

self.ProjectsArray.sorted(by: { (project, project2) -> Bool in       
   return project.timestamp?.intValue < project2.timestamp?.intValue     
   })

Is there a better way to sort an array? What am I'm doing wrong?

回答1:

EDIT- According to your comments you want to sort in place, so I am updating to sort in place.

Your timestamp variable is an Optional, so you may be comparing nil to nil, or nil to an Int. You can either unwrap these safely and provide a sort order in the case that one is nil, or you can use a nil-coalescing operator to treat nil value as some default Int like 0. The two options look like this:

Optional unwrapping:

self.ProjectsArray.sort(by: { (project, project2) -> Bool in
    if let timestamp1 = project.timestamp, let timestamp2 = project2.timestamp {
       return timestamp1.intValue < timestamp2.intValue
    } else {
        //At least one of your timestamps is nil.  You have to decide how to sort here.
        return true
    }    
})

Nil-coalescing operators:

self.ProjectsArray.sort(by: { (project, project2) -> Bool in  
    //Treat nil values as 0s and sort accordingly     
    return (project.timestamp?.intValue ?? 0) < (project2.timestamp?.intValue ?? 0)     
})