ios – 按字母顺序排列数字

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 at https://stackoverflow.com/a/39748677/1187415.

相关文章
相关标签/搜索