作者:梦露的殇_192 | 来源:互联网 | 2023-07-29 19:31
IwanttheSwiftversionofthiscode:我想要这个代码的Swift版本:NSArray*sortedNames[namessortedArrayUs
I want the Swift version of this code:
我想要这个代码的Swift版本:
NSArray *sortedNames = [names sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
8 个解决方案
7
Most efficient way of sorting in SWIFT
The use of Operator Overloading is the most efficient way to sort Strings in Swift language.
使用运算符重载是在Swift语言中排序字符串的最有效方法。
// OPERATOR OVERLOADING
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
var sortedNames = sorted(names, <)
var reverseOrder = sorted(names, >)
In above code >
and <
operators are overloaded in Swift to sort Strings.
在上面的代码中,>和 <运算符在swift中被重载以对字符串进行排序。
I have test the code in Playground and conclude that when we use operator overloading it is best for sorting Strings.
我在操场上测试了代码,并得出结论,当我们使用操作符重载时,它最适合对字符串进行排序。
Copy below to Playground.
复制下面的游乐场。
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
var reversed = sorted (names,
// This is a closure
{ (s1 : String, s2 : String) -> Bool in
return s1 > s2
}
)
println(reversed)
var reverseOrder = sorted(names, {s1, s2 in s1 > s2})
var reverseOrder2 = sorted(names, { $0 > $1} )
// OPERATOR OVERLOADING
var reverseOrder3 = sorted(names, >)
The conclusion from Playground:
结论从操场上:
From above image you can see that all other ways needs to enumerate loops for sorting 5 strings. Where as when we use Operator overloading it does not required to enumerate loop to sort strings.
从上面的图像中可以看到,所有其他的方法都需要枚举循环来排序5个字符串。当我们使用操作符重载时,不需要枚举循环来排序字符串。
Referenced from Swift documentation
从迅速引用文档