如何用Swift排序数组

时间:2022-06-15 16:00:10

I want the Swift version of this code:

我想要这个代码的Swift版本:

NSArray *sortedNames = [names sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

8 个解决方案

#1


67  

var names = [ "Alpha", "alpha", "bravo"]
var sortedNames = names.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }

Update: Providing explanation as per recommendation of a fellow SO user.

更新:根据SO用户的推荐提供解释。

Unlike ObjC, in Swift you have sorted() (and sort()) method that takes a closure that you supply that returns a Boolean value to indicate whether one element should be before (true) or after (false) another element. The $0 and $1 are the elements to compare. I used the localizedCaseInsensitiveCompare to get the result you are looking for. Now, localizedCaseInsensitiveCompare returns the type of ordering, so I needed to modify it to return the appropriate bool value.

与ObjC不同的是,在Swift中,您有sort()(和sort())方法,它接受您提供的闭包,返回一个布尔值,以指示一个元素应该在(true)之前还是在(false)之后。$0和$1是要比较的元素。我使用了本地化的caseinsensitivecompare来得到你想要的结果。现在,本地化后的caseinsensitivecompare返回排序类型,因此我需要修改它以返回适当的bool值。

Update for Swift 2: sorted and sort were replaced by sort and sortInPlace

Swift 2的更新:排序和排序被排序和排序所取代

#2


20  

Sorting an Array in Swift

Define a initial names array:

定义一个初始名称数组:

var names = [ "gamma", "Alpha", "alpha", "bravo"]

Method 1:

方法1:

var sortedNames = sorted(names, {$0 < $1})
// sortedNames becomes "[Alpha, alpha, bravo, gamma]"

This can be further simplified to:

这可进一步简化为:

var sortedNames = sorted(names, <)
// ["Alpha", "alpha", "bravo", "gamma"]
var reverseSorted = sorted(names, >)
// ["gamma", "bravo", "alpha", "Alpha"]

Method 2:

方法2:

names.sort(){$0 < $1}
// names become sorted as this --> "[Alpha, alpha, bravo, gamma]"

#3


17  

If your array does not contain Custom Objects (just a string or number type):

如果您的数组不包含自定义对象(只是一个字符串或数字类型):

var sortedNames = sorted(names, <)

Otherwise if you create a Custom Data Object Class containing custom properties inside:

否则,如果您创建一个自定义数据对象类,其中包含自定义属性:

customDataObjectArray.sort({ $0.customProperty < $1.customProperty })

#4


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中被重载以对字符串进行排序。< p>

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:

结论从操场上:

如何用Swift排序数组

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

从迅速引用文档

#5


4  

If you want to sort your array in ascending order then use below syntax:

如果要按升序排列数组,请使用以下语法:

var arrayName = sorted(arrayName, <)

as the sorted() is the predefined function in swift and < is used to indicate that the array should be sorted in ascending order. If you want to sort the array in descending order then simply replace < with > as I have shown below:

作为排序的()是swift和 <的预定义函数,用于指示数组应该按升序排序。如果您想按降序排列数组,那么只需将<和> 替换为如下所示:

var arrayName = sorted(arrayName, >)

#6


2  

You can usually use the built-in

您通常可以使用内置的

func sort<T : Comparable>(inout array: [T])

but if you want to use localizedCaseInsensitiveCompare:, your code can be translated directly using NSArray.

但是如果您想使用本地化的caseinsensitivecompare:,您的代码可以直接使用NSArray进行翻译。

#7


2  

Any method that can be used with Objective-C sortedArrayUsingSelector: can be used with Swift sort (or sorted) provided the type of thing in the array is known. So, in your code:

任何可以与Objective-C sortedArrayUsingSelector一起使用的方法都可以与Swift排序(或排序)一起使用,前提是数组中的内容的类型是已知的。所以,在你的代码:

var arr : [String] = // ...
// it is an array of String, so we can use localizedCaseInsensitiveCompare:
sort(&arr) {return $0.localizedCaseInsensitiveCompare($1) == .OrderedAscending}

Similarly:

类似的:

var events : [EKEvent] = // ...
sort(&events) {return $0.compareStartDateWithEvent($1) == .OrderedAscending}

#8


1  

In Swift-

在斯威夫特-

let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let sortedStudents = students.sorted()
print(sortedStudents)
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"

To sort the elements of your sequence in descending order, pass the greater-than operator (>) to the sorted(isOrderedBefore:) method.

要按降序对序列中的元素进行排序,请将大于运算符(>)传递给sort (isOrderedBefore:)方法。

let descendingStudents = students.sorted(isOrderedBefore: >)
print(descendingStudents)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"

#1


67  

var names = [ "Alpha", "alpha", "bravo"]
var sortedNames = names.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }

Update: Providing explanation as per recommendation of a fellow SO user.

更新:根据SO用户的推荐提供解释。

Unlike ObjC, in Swift you have sorted() (and sort()) method that takes a closure that you supply that returns a Boolean value to indicate whether one element should be before (true) or after (false) another element. The $0 and $1 are the elements to compare. I used the localizedCaseInsensitiveCompare to get the result you are looking for. Now, localizedCaseInsensitiveCompare returns the type of ordering, so I needed to modify it to return the appropriate bool value.

与ObjC不同的是,在Swift中,您有sort()(和sort())方法,它接受您提供的闭包,返回一个布尔值,以指示一个元素应该在(true)之前还是在(false)之后。$0和$1是要比较的元素。我使用了本地化的caseinsensitivecompare来得到你想要的结果。现在,本地化后的caseinsensitivecompare返回排序类型,因此我需要修改它以返回适当的bool值。

Update for Swift 2: sorted and sort were replaced by sort and sortInPlace

Swift 2的更新:排序和排序被排序和排序所取代

#2


20  

Sorting an Array in Swift

Define a initial names array:

定义一个初始名称数组:

var names = [ "gamma", "Alpha", "alpha", "bravo"]

Method 1:

方法1:

var sortedNames = sorted(names, {$0 < $1})
// sortedNames becomes "[Alpha, alpha, bravo, gamma]"

This can be further simplified to:

这可进一步简化为:

var sortedNames = sorted(names, <)
// ["Alpha", "alpha", "bravo", "gamma"]
var reverseSorted = sorted(names, >)
// ["gamma", "bravo", "alpha", "Alpha"]

Method 2:

方法2:

names.sort(){$0 < $1}
// names become sorted as this --> "[Alpha, alpha, bravo, gamma]"

#3


17  

If your array does not contain Custom Objects (just a string or number type):

如果您的数组不包含自定义对象(只是一个字符串或数字类型):

var sortedNames = sorted(names, <)

Otherwise if you create a Custom Data Object Class containing custom properties inside:

否则,如果您创建一个自定义数据对象类,其中包含自定义属性:

customDataObjectArray.sort({ $0.customProperty < $1.customProperty })

#4


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中被重载以对字符串进行排序。< p>

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:

结论从操场上:

如何用Swift排序数组

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

从迅速引用文档

#5


4  

If you want to sort your array in ascending order then use below syntax:

如果要按升序排列数组,请使用以下语法:

var arrayName = sorted(arrayName, <)

as the sorted() is the predefined function in swift and < is used to indicate that the array should be sorted in ascending order. If you want to sort the array in descending order then simply replace < with > as I have shown below:

作为排序的()是swift和 <的预定义函数,用于指示数组应该按升序排序。如果您想按降序排列数组,那么只需将<和> 替换为如下所示:

var arrayName = sorted(arrayName, >)

#6


2  

You can usually use the built-in

您通常可以使用内置的

func sort<T : Comparable>(inout array: [T])

but if you want to use localizedCaseInsensitiveCompare:, your code can be translated directly using NSArray.

但是如果您想使用本地化的caseinsensitivecompare:,您的代码可以直接使用NSArray进行翻译。

#7


2  

Any method that can be used with Objective-C sortedArrayUsingSelector: can be used with Swift sort (or sorted) provided the type of thing in the array is known. So, in your code:

任何可以与Objective-C sortedArrayUsingSelector一起使用的方法都可以与Swift排序(或排序)一起使用,前提是数组中的内容的类型是已知的。所以,在你的代码:

var arr : [String] = // ...
// it is an array of String, so we can use localizedCaseInsensitiveCompare:
sort(&arr) {return $0.localizedCaseInsensitiveCompare($1) == .OrderedAscending}

Similarly:

类似的:

var events : [EKEvent] = // ...
sort(&events) {return $0.compareStartDateWithEvent($1) == .OrderedAscending}

#8


1  

In Swift-

在斯威夫特-

let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let sortedStudents = students.sorted()
print(sortedStudents)
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"

To sort the elements of your sequence in descending order, pass the greater-than operator (>) to the sorted(isOrderedBefore:) method.

要按降序对序列中的元素进行排序,请将大于运算符(>)传递给sort (isOrderedBefore:)方法。

let descendingStudents = students.sorted(isOrderedBefore: >)
print(descendingStudents)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"