Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Sort array of versions as strings

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?

like image 462
John Doe Avatar asked Sep 03 '25 01:09

John Doe


2 Answers

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.

like image 75
Rob Avatar answered Sep 07 '25 07:09

Rob


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

like image 32
Code Different Avatar answered Sep 07 '25 05:09

Code Different