Last active
November 21, 2017 08:14
-
-
Save lukagabric/dbd61e73b76c8338af4b15995aab161e to your computer and use it in GitHub Desktop.
Comparing version strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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