我在使用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
}
Run Code Online (Sandbox Code Playgroud)
为了让事情更加奇怪,如果我首先使用封面的长形式然后使用简写形式再次排序,它工作正常!
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
}
Run Code Online (Sandbox Code Playgroud)
所以,最好的情况,我做错了什么,并学习一些东西.最糟糕的情况是,这只是Xcode或Swift的一个愚蠢的错误.
有任何想法吗?
erg*_*oon -1
正如 @Martin R 指出的,问题的根源在于,您正在 Swift String 类型上调用 NSString 的方法。
这很好用
names.sort {
$0 <= $1
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
624 次 |
| 最近记录: |