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?
Asked
Active
Viewed 1,842 times
3

MatterGoal
- 16,038
- 19
- 109
- 186
-
The referenced question was originally for Objective-C, but has a [Swift answer](http://stackoverflow.com/a/29230214/1187415) as well. – Martin R Oct 16 '15 at 11:58
-
I saw only the Objective-C answer, shame on me :/ – MatterGoal Oct 16 '15 at 12:37
1 Answers
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