3

I need to compare 2 strings that represent versions, like 1.2.4 and 2.3.6. I'd like to know if already exists some similar implementation in swift. Maybe something similar to the systemInfo function for UIDevice. If not, which is in your opinion a good way to perform this check?

MatterGoal
  • 16,038
  • 19
  • 109
  • 186

1 Answers1

12

A good way is the compare: method with option .NumericSearch

let version1 = "1.2.4"
let version2 = "2.3.6"

let result = version1.compare(version2, options: .numeric)
switch result {
case .orderedSame : print("versions are equal")
case .orderedAscending : print("version1 is less than version2")
case .orderedDescending : print("version1 is greater than version2")
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • It works. I found this strange issue though. IF I compare 2.0 with 2.0.0 this function returns that 2.0.0 is greater than 2.0 – MatterGoal Oct 16 '15 at 14:10
  • Yes, but usually version numbers with minor and patch value of zero are displayed as x.0 rather than x.0.0 and x.0.1 > x.0 is correctly recognized. – vadian Oct 16 '15 at 14:18