我目前正在尝试将一些 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 的类型Date
编译器抱怨以下错误消息
传递给不带参数的调用的参数
知道我做错了什么吗?
我真的不明白编译器想告诉什么。
排序需要一个块,我通过了它,一切都应该没问题。
UPDATE
我发现了错误。 Swift 将所有 NSDate 属性转换为 Date,我们得到了一个名为的扩展isAfter在 NSDate 上。所以编译器再也找不到isAfter了。编译器错误消息完全具有误导性。
我会用sorted(by: )
i.e.
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}))
...结果是
[锻炼装备(名称:“滑雪板”,最后使用时间:2017-02-08 05:00:00
+0000),ExerciseEquipment(名称:“山地自行车”,lastUsage:2016-10-30 04:00:00 +0000),ExerciseEquipment(名称:“高尔夫俱乐部”,lastUsage:
2015-03-16 04:00:00 +0000),ExerciseEquipment(名称:“曲棍球棒”,
最后使用时间:2010-09-21 04:00:00 +0000),ExerciseEquipment(名称:“网球
球拍”,最后使用:2003-06-30 04:00:00 +0000)]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)