小编典典

用数字按字母顺序对数组排序

swift

myArray = [Step 6, Step 12, Step 5, Step 14, Step 4, Step 11, Step 16, Step 9,
Step 3, Step 13, Step 8, Step 2, Step 10, Step 7, Step 1, Step 15]

如何以这种方式在上面对这个数组排序?

[Step 1, Step 2, Step 3, Step 4, ....]

我很快使用了此功能,sort(&myArray,{ $0 < $1 })但它是按这种方式排序的

[Step 1, Step 10, Step 11, Step 12, Step 13, Step 14, Step 15, Step 16, Step 2, 
 Step 3, Step 4, Step 5, Step 6, Step 7, Step 8, Step 9]

阅读 347

收藏
2020-07-07

共1个答案

小编典典

另一个变种是使用
localizedStandardCompare:。从文档中:

只要在类似Finder排序的列表和表中显示文件名或其他字符串,就应使用此方法。

这将根据当前语言环境对字符串进行排序。例:

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

let ans = sorted(myArray,{ (s1, s2) in 
    return s1.localizedStandardCompare(s2) == NSComparisonResult.OrderedAscending
})

println(ans)
// [Step 6, Step 10, Step 12]

更新: 上面的答案是很老的,对于Swift 1.2。一个 斯威夫特3 版(感谢@Ahmad):

let ans = myArray.sorted {
    (s1, s2) -> Bool in return s1.localizedStandardCompare(s2) == .orderedAscending
}
2020-07-07