Swift - Sort array of versions as strings

Viewed 920

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?

4 Answers

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
}

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"]
Related