Skip to content

Instantly share code, notes, and snippets.

@adriatikgashi
Created May 14, 2020 15:40
Show Gist options
  • Save adriatikgashi/222291bff2643d7f2c436ef886bd8d75 to your computer and use it in GitHub Desktop.
Save adriatikgashi/222291bff2643d7f2c436ef886bd8d75 to your computer and use it in GitHub Desktop.
enum AppVersionComparisonResult {
case greater
case smaller
case equal
case unknown
}
class AppVersion {
var major: Int?
var minor: Int?
var patch: Int?
init(_ versionString: String) {
let array: [Int?] = versionString.split(separator: ".").map{ Int(String($0)) }
if array.indices.contains(0), let value = array[0] {
major = value
}
if array.indices.contains(1), let value = array[1] {
minor = value
}
if array.indices.contains(2), let value = array[2] {
patch = value
}
}
func compare(to version: AppVersion) -> AppVersionComparisonResult {
// Major
guard let major1 = major else {
if version.major != nil {
return .smaller
} else {
return .unknown
}
}
guard let major2 = version.major else { return .greater }
if major1 > major2 { return .greater } else if major2 > major1 { return .smaller }
// Minor
guard let minor1 = minor else {
if version.minor != nil {
return .smaller
} else {
return .equal
}
}
guard let minor2 = version.minor else { return .greater }
if minor1 > minor2 { return .greater } else if minor2 > minor1 { return .smaller }
// Patch
guard let patch1 = patch else {
if version.patch != nil {
return .smaller
} else {
return .equal
}
}
guard let patch2 = version.patch else { return .greater }
if patch1 > patch2 { return .greater } else if patch2 > patch1 { return .smaller } else { return .equal }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment