gpt4 book ai didi

ios - 按字母顺序和数字对数组进行排序

转载 作者:行者123 更新时间:2023-11-30 14:15:46 25 4
gpt4 key购买 nike

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, ....]

我在 swift 中使用了这个函数 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]

最佳答案

另一种变体是使用 localizedStandardCompare: 。来自文档:

This method should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate.

这将根据当前区域设置对字符串进行排序。示例:

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 来说已经很旧了。 Swift 3 版本是(感谢@Ahmad):

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

有关不同的方法,请参阅 https://stackoverflow.com/a/31209763/1187415 ,翻译为 Swift 3 https://stackoverflow.com/a/39748677/1187415 .

关于ios - 按字母顺序和数字对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31211196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com