我有一个随机排序的字符串数组(应用程序的版本),如:
var arrayOfStrings = ["2.12.5", "2.12.10", "2.2", "2.11.8"]
排序后的数组应为[" 2.2"," 2.12.10"," 2.12.5"," 2.11.8&#34 ;](按最近的顺序排列)。我试图对它进行排序。
编辑:我的坏,排序的数组实际上应该是[" 2.12.10"," 2.12.5"," 2.11.8",&# 34; 2.2&#34]。使用上面的解决方案。//Compare by string
array.sortInPlace({ //This returns ["2.2", "2.12.5", "2.12.10", "2.11.8"]
$0 > $1
})
//Compare by int
array.sortInPlace({ //This returns ["2.12.10", "2.12.5", "2.11.8", "2.2"]
Int($0.stringByReplacingOccurrencesOfString(".", withString: "")) > Int($1.stringByReplacingOccurrencesOfString(".", withString: ""))
})
这些都没有正常工作。返回正确数组的最佳方法是什么?
答案 0 :(得分:4)
最简单的选择是将compare
与.NumericSearch
:
arrayOfStrings.sortInPlace { $0.compare($1, options: .NumericSearch) == .OrderedAscending }
显然,如果您想按降序排列,请使用.OrderedDescending
。
答案 1 :(得分:2)
您必须将版本字符串拆分为其组件,将它们转换为数字并比较它们的数值。试试这个:
2.1a
这显然无法处理3.14b123
或{{1}}
答案 2 :(得分:0)
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
}
答案 3 :(得分:0)
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"]