简体   繁体   English

按字母顺序对数组进行排序Swift3

[英]Sort Array Alphanumerically Swift3

I have a function I was using in Xcode 8 Beta, which sorted an array alphabetically then numerically. 我有一个在Xcode 8 Beta中使用的函数,该函数先按字母顺序然后按数字顺序对数组进行排序。

The function I used was: 我使用的功能是:

func sortArray(arrayToSort: [String])->[String]{

let sortedArray = arrayToSort.sorted {
(first, second) in
first.compare(second, options: .numericSearch) == ComparisonResult.orderedAscending
}
   print(sortedArray)
   return sortedArray
}

However this doesnt work anymore. 但是,这不再起作用了。 Does anyone had any idea how I can do this in Swift 3? 有谁知道我如何在Swift 3中做到这一点?

There is a function sort() through which you can sort your array like this 有一个函数sort() ,您可以通过它对数组进行排序

var arrSort = ["Rajat", "Test", "Sort", "Array","2","6"]
arrSort.sort()
print(arrSort)

After some further digging I found an answer: 经过进一步的挖掘,我找到了答案:

let myArray = ["Step 6", "Step 12", "Step 10"]

let sortedArray = myArray.sorted {
$0.compare($1, options: .numeric) == .orderedAscending
}

print(sortedArray) // ["Step 6", "Step 10", "Step 12"]

This was based on Martin R, and Duncan C's posts. 这是基于Martin R和Duncan C的帖子。

Thank You! 谢谢! ^_______^ ^ _______ ^

You can try this example as below: 您可以尝试以下示例:

func sortArray(arrayToSort: [String])->[String] {
   let sortedArray = arrayToSort.sorted(by:) {
     (first, second) in
     first.compare(second, options: .numeric) == ComparisonResult.orderedAscending
   }
   print(sortedArray)
   return sortedArray
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM