我在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的愚蠢错误。
有任何想法吗?
最佳答案
正如@Martin R所指出的那样,问题的根源在于,您正在从NSString调用Swift String类型的方法。
这很好
names.sort {
$0 <= $1
}
关于Swift Array.sort()将不接受简写形式的闭包,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30699222/