Pavan Pavan - 5 months ago 7
Swift Question

Version checker fails when comparing numbered strings "16" != "16.0" using the NSComparisonResult class

Consider this block of code which uses NSComparisonResult, what can I do to make this return false? This should be able to parse strings that have multiple decimal points.

let currentInstalledVersion = "16"
let currentAppStoreVersion = "16.0"

var newVersionExists = false

if (currentInstalledVersion.compare(currentAppStoreVersion, options: .NumericSearch) == NSComparisonResult.OrderedAscending) {
newVersionExists = true
}


newVersionExists
Outputs to true in playgrounds.

Currently

Answer

Your problem is more nuanced since your version strings can have varying numbers of subversion indicators. Try this:

func compareVersion(v1: String, toVersion v2: String) -> NSComparisonResult {
    var components1 = v1.componentsSeparatedByString(".")
    var components2 = v2.componentsSeparatedByString(".")
    let maxCount = max(components1.count, components2.count)

    while components1.count < maxCount { components1.append("0") }
    while components2.count < maxCount { components2.append("0") }

    for i in 0..<maxCount {
        let order = components1[i].compare(components2[i], options: .NumericSearch)
        if order != .OrderedSame {
            return order
        }
    }

    return .OrderedSame
}

compareVersion("16", toVersion: "16.0") // .OrderedSame
compareVersion("17", toVersion: "17.0.0.1") // .OrderedAscending
compareVersion("18.1", toVersion: "18.0.0.1") // .OrderDescending
compareVersion("19a2", toVersion: "19a10") // .OrderedAscending
Comments