I have an array of strings (of an app's versions) randomly ordered like:
var array = ["2.12.5", "2.12.10", "2.2", "2.11.8"]
The sorted array should be ["2.12.10", "2.12.5", "2.11.8", "2.2"] (ordered by most recent). I am trying to sort it.
//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)
}
None of this is working properly. What is the best way to return the correct array?
The easiest option is to use compare
with .numeric
:
array.sort { $0.compare($1, options: .numeric) == .orderedDescending }
Obviously, if you want it in ascending order, use .orderedAscending
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With