Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Comparing version strings
import UIKit
import Foundation
func compareVersions(version1: String, version2: String) -> ComparisonResult {
let version1Components = version1.components(separatedBy: ".")
let version2Components = version2.components(separatedBy: ".")
let length = max(version1Components.count, version2Components.count)
for i in 0 ..< length {
let version1Component: Int
let version2Component: Int
if i < version1Components.count {
version1Component = Int(version1Components[i]) ?? 0
} else {
version1Component = 0
}
if i < version2Components.count {
version2Component = Int(version2Components[i]) ?? 0
} else {
version2Component = 0
}
guard version1Component != version2Component else { continue }
return version1Component < version2Component ? .orderedAscending : .orderedDescending
}
return .orderedSame
}
func performCustomAndStringVersionComparisons(version1: String, version2: String) -> (String, String) {
let comparison = compareVersions(version1: version1, version2: version2)
let comparisonDescription = getComparisonDescription(comparison: comparison)
let numericStringComparison = version1.compare(version2, options: .numeric)
let numericStringComparisonDescription = getComparisonDescription(comparison: numericStringComparison)
return (comparisonDescription, numericStringComparisonDescription)
}
func getComparisonDescription(comparison: ComparisonResult) -> String {
switch comparison {
case .orderedSame:
return "Same"
case .orderedAscending:
return "Lower"
case .orderedDescending:
return "Greater"
}
}
let comparisonWhenDifferent = performCustomAndStringVersionComparisons(version1: "1.0.1", version2: "1.0.3")
let comparisonWhenSame = performCustomAndStringVersionComparisons(version1: "1.0", version2: "1.0")
let comparisonWhenShouldBeSame1 = performCustomAndStringVersionComparisons(version1: "1.0", version2: "1.0.0")
let comparisonWhenShouldBeSame2 = performCustomAndStringVersionComparisons(version1: "1.0.0", version2: "1.0")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment