-1

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

Could someone explain why that is the case?

Pavan
  • 17,840
  • 8
  • 59
  • 100
  • @ColGraff did you down vote? Sure I can post the text version right now – Pavan Jun 19 '16 at 14:19
  • Since downvotes are anonymous if I say yes or no you wouldn't know if I was lying or telling the truth. I posted my suggestion in order to help you get faster and more answers. Hopefully the other question of which this is a duplicate and the answer here gave you the help you needed. –  Jun 19 '16 at 15:07
  • The question you referenced was not a duplicate. Take the time to read my question to understand the difference. Thank you for your time. – Pavan Jun 19 '16 at 16:20
  • The referenced question is similar to your question and has an answer which works for your problem (although it does need to be updated to a newer version of the language): http://stackoverflow.com/a/32062641/887210 –  Jun 19 '16 at 19:43

1 Answers1

1

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
Code Different
  • 90,614
  • 16
  • 144
  • 163