Bool in-6ren">
gpt4 book ai didi

arrays - 数组排序错误 : "Binary operator ' <' cannot be applied to two ' Int ?' operands"

转载 作者:行者123 更新时间:2023-11-28 15:11:20 25 4
gpt4 key购买 nike

这是用于按 tableView 时间戳中的每个单元格对数组进行排序的代码。

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

是否有更好的方法对数组进行排序?我做错了什么?

最佳答案

编辑- 根据您的意见,您希望就地排序,因此我更新为就地排序。

您的时间戳变量是一个可选,因此您可能会将nilnil 进行比较,或者将nil 与一个 Int。您可以安全地解包这些并在一个为 nil 的情况下提供排序顺序,或者您可以使用 nil 合并运算符将 nil 值视为一些默认 Int,如 0。这两个选项看起来像这样:

可选的展开:

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

关于arrays - 数组排序错误 : "Binary operator ' <' cannot be applied to two ' Int ?' operands",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47582389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com