问题
I have an array of strings (of an app's versions) randomly ordered like:
var arrayOfStrings = ["2.12.5", "2.12.10", "2.2", "2.11.8"]
The sorted array should be ["2.2", "2.12.10", "2.12.5", "2.11.8"] (ordered by most recent). I am trying to sort it.
EDIT: My bad, the sorted array should actually be ["2.12.10", "2.12.5", "2.11.8", "2.2"]. Use the solution above.
//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: ""))
})
None of this is working properly. What is the best way to return the correct array?
回答1:
The easiest option is to use compare
with .NumericSearch
:
arrayOfStrings.sortInPlace { $0.compare($1, options: .NumericSearch) == .OrderedAscending }
Obviously, if you want it in descending order, use .OrderedDescending
.
回答2:
You have to split the version string into its components, convert them to numbers and compare their numeric values. Try this:
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
}
This obviously cannot handle version numbers like 2.1a
or 3.14b123
回答3:
Swift 4 version:
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
}
回答4:
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"]
来源:https://stackoverflow.com/questions/35815469/swift-sort-array-of-versions-as-strings