我有一个(应用程序版本的)字符串数组,随机排序如下:
var array = ["2.12.5", "2.12.10", "2.2", "2.11.8"]
排序后的数组应为 ["2.12.10"、"2.12.5"、"2.11.8"、"2.2"](按最新排序)。我正在尝试对其进行排序。
//Compare by string
array.sort { //This returns ["2.2", "2.12.5", "2.12.10", "2.11.8"]
$0 > $1
}
//Compare by int
array.sort { //This returns ["2.12.10", "2.12.5", "2.11.8", "2.2"]
(Int($0.replacingOccurrences(of: ".", with: "")) ?? 0) > (Int($1.replacingOccurrences(of: ".", with: "")) ?? 0)
}
这些都无法正常工作。返回正确数组的最佳方法是什么?
最简单的选择是将compare
与.numeric
一起使用:
array.sort { $0.compare($1, options: .numeric) == .orderedDescending }
显然,如果您希望按升序排列,请使用 .orderedAscending
.
您必须将版本字符串拆分为其组件,将它们转换为数字并比较它们的数值。试试这个:
var arrayOfStrings = ["2.12.5", "2.12.10", "2.2", "2.11.8"]
arrayOfStrings.sortInPlace {
let v0 = ($0 as NSString).componentsSeparatedByString(".")
let v1 = ($1 as NSString).componentsSeparatedByString(".")
for i in 0..<min(v0.count, v1.count) {
if v0[i] != v1[i] {
return Int(v0[i]) < Int(v1[i])
}
}
return v0.count < v1.count
}
这显然无法处理2.1a
或3.14b123
等版本号
Swift 4 版本:
var arrayOfStrings = ["2.12.5", "2.12.10", "2.2", "2.11.8"]
arrayOfStrings.sorted { (lhs, rhs) in
let lhsc = lhs.components(separatedBy: ".")
let rhsc = rhs.components(separatedBy: ".")
for i in 0..<min(lhsc.count, rhsc.count) where lhsc[i] != rhsc[i] {
return (Int(lhsc[i]) ?? 0) < (Int(rhsc[i]) ?? 0)
}
return lhsc.count < rhsc.count
}
Swift 4.2
:var arrayOfStrings = ["1.2.1", "1.0.6", "1.1.10"]
arrayOfStrings.sort { (a, b) -> Bool in
a.compare(b, options: String.CompareOptions.numeric, range: nil, locale: nil) == .orderedAscending
}
print(arrayOfStrings) // ["1.0.6", "1.1.10", "1.2.1"]