可选的展开方式: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 }})零销售商: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)})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? 解决方案 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)}) 这篇关于数组排序错误:“二进制运算符'&lt;'不能应用于两个'Int?'操作数"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-14 01:32