This question already has an answer here:
这个问题在这里已有答案:
- Sorting array alphabetically with number 7 answers
- 按字母顺序排列数组7号答案
I have an array of strings,
我有一个字符串数组,
Array=[ "10", "1", "101", "NA", "100", "20", "210", "200", "NA", "7" ]
I would like to get the output sorted in ascending as,
我想将输出按升序排序为,
Sorted=[ "1", "7", "10", "20", "100", "101", "200", "210", "NA", "NA" ]
I tried using the sorted command but it does not work when it encounters more than 2 digits e.g.: 100, 101, 200 etc.
我尝试使用sorted命令,但遇到超过2位数时不起作用,例如:100,101,200等。
Array.sorted { $0? < $1? }
What would be the simple way to get this?
得到这个的简单方法是什么?
1 个解决方案
#1
24
You can use String method localizedStandardCompare
您可以使用String方法localizedStandardCompare
let array = [ "10", "1", "101", "NA", "100", "20", "210", "200", "NA", "7" ]
let sorted = array.sorted {$0.localizedStandardCompare($1) == .orderedAscending}
print(sorted) // ["1", "7", "10", "20", "100", "101", "200", "210", "NA", "NA"]
#1
24
You can use String method localizedStandardCompare
您可以使用String方法localizedStandardCompare
let array = [ "10", "1", "101", "NA", "100", "20", "210", "200", "NA", "7" ]
let sorted = array.sorted {$0.localizedStandardCompare($1) == .orderedAscending}
print(sorted) // ["1", "7", "10", "20", "100", "101", "200", "210", "NA", "NA"]