问题
I am currently trying to port some Swift 2 code to Swift 3.0.
Here is one line of code that is driving me crazy.
public private(set) var searchHistory: [SearchHistoryEntry] = [SearchHistoryEntry]() // Struct that is cComparable
....
...
searchHistory.sortInPlace({ $0.lastUsage.isAfter($1.lastUsage) })
This is my Swift 3.0 Version
searchHistory.sort(by:{ $0.lastUsage.isAfter($1.lastUsage) })
lastUsage is of Type Date
The Compiler complains with the following error message
Argument passed to call that takes no arguments
Any Ideas what I am doing wrong? I really don not understand what the compiler wants to tell. Sort takes a block and I pass it, everything should be fine.
UPDATE
I found the mistake. Swift converted all NSDate properties to Date and we got an extension called isAfter on NSDate. So the compiler could not found isAfter anymore. The compiler error message was completely misleading.
回答1:
I would use sorted(by: ) i.e.
searchHistory.sorted(by: {$0.lastUsage > $1.lastUsage})
Full working example:
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}))
...results in
[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)]
回答2:
Just got to the same error. My previous code in Swift was:
let sorted = array.sorted {
$0.characters.count < $1.characters.count
}
However, it is not working anymore. Looks like they've updated sorted() with arguments to sorted(by: )
The following works for me now:
let sorted = array.sorted(by: {x, y -> Bool in
x.characters.count < y.characters.count
})
来源:https://stackoverflow.com/questions/38995107/swift-3-0-sort-argument-passed-to-call-that-takes-no-arguments