我目前正在尝试将一些 Swift 2 代码移植到 Swift 3.0。
这是让我发疯的一行代码。
public private(set) var searchHistory: [SearchHistoryEntry] = [SearchHistoryEntry]() // Struct that is cComparable
....
...
searchHistory.sortInPlace({ $0.lastUsage.isAfter($1.lastUsage) })
这是我的 Swift 3.0 版本
searchHistory.sort(by:{ $0.lastUsage.isAfter($1.lastUsage) })
lastUsage 的类型是日期
编译器提示以下错误信息
传递给不带参数的调用的参数
任何想法我做错了什么? 我真的不明白编译器想告诉什么。 排序需要一个 block ,我通过了它,一切都应该没问题。
更新
我发现了错误。 Swift 将所有 NSDate 属性转换为 Date,我们在 NSDate 上得到了一个名为 isAfter 的扩展。所以编译器再也找不到 isAfter 了。编译器错误消息完全具有误导性。
最佳答案
我会使用 sorted(by: )
即
searchHistory.sorted(by: {$0.lastUsage > $1.lastUsage})
完整的工作示例:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
struct ExerciseEquipment
{
let name: String
let lastUsage: Date
}
let myExerciseEquipment =
[
ExerciseEquipment(name: "Golf Clubs", lastUsage: dateFormatter.date(from: "03-16-2015")!),
ExerciseEquipment(name: "Tennis Racket", lastUsage: dateFormatter.date(from: "06-30-2003")!),
ExerciseEquipment(name: "Skis", lastUsage: dateFormatter.date(from: "02-08-2017")!),
ExerciseEquipment(name: "Hockey Stick", lastUsage: dateFormatter.date(from: "09-21-2010")!),
ExerciseEquipment(name: "Mountain Bike", lastUsage: dateFormatter.date(from: "10-30-2016")!)
]
print(myExerciseEquipment.sorted(by: {$0.lastUsage > $1.lastUsage}))
...结果
[ExerciseEquipment(name: "Skis", lastUsage: 2017-02-08 05:00:00 +0000), ExerciseEquipment(name: "Mountain Bike", lastUsage: 2016-10-30 04:00:00 +0000), ExerciseEquipment(name: "Golf Clubs", lastUsage: 2015-03-16 04:00:00 +0000), ExerciseEquipment(name: "Hockey Stick", lastUsage: 2010-09-21 04:00:00 +0000), ExerciseEquipment(name: "Tennis Racket", lastUsage: 2003-06-30 04:00:00 +0000)]
关于Swift 3.0 排序 - 传递给不带参数的调用的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38995107/