我遇到了Array.sort()函数的一个奇怪问题。它没有接受速记关闭。使用速记闭包时,Xcode会抱怨以下消息:Cannot invoke 'sort' with an argument list of type '((_, _) -> _)'
但它适用于同一个闭包的较长形式。
var names = ["Al", "Mike", "Clint", "Bob"]
// This `sort()` function call fails:
names.sort {
$0.localizedCaseInsensitiveCompare($1) == .OrderedAscending
}
// This `sort()` function call works:
names.sort { (first: String, second: String) in
return first.localizedCaseInsensitiveCompare(second) == .OrderedAscending
}
为了让事情更加奇怪,如果我首先使用封面的长形式然后再使用简写形式再次排序,它就可以正常工作!
var names = ["Al", "Mike", "Clint", "Bob"]
// Works fine, orders the array alphabetically
names.sort { (first: String, second: String) in
return first.localizedCaseInsensitiveCompare(second) == .OrderedAscending
}
// This shorthand version now works as well, reversing the order of the array
names.sort {
$0.localizedCaseInsensitiveCompare($1) == .OrderedDescending
}
所以,最好的情况是,我做错了什么并开始学习。最糟糕的情况是,这只是Xcode或Swift的一个愚蠢的错误。
有什么想法吗?
答案 0 :(得分:-1)
as @Martin R pointed out, the root of the problem is, that you're calling a method from NSString on a Swift String type.
this works fine
names.sort {
$0 <= $1
}