Skip to content

Instantly share code, notes, and snippets.

@asalom
Created May 17, 2017 07:56
Show Gist options
  • Save asalom/cc5e1fcfbb074d985dd1dc846fd5573f to your computer and use it in GitHub Desktop.
Save asalom/cc5e1fcfbb074d985dd1dc846fd5573f to your computer and use it in GitHub Desktop.
Compare version numbers for the format MAJOR.MINOR.REVISION in Swift
public struct VersionNumber: Equatable, Comparable {
public let version: String
public init(version: String) {
self.version = version
}
}
// Returns 1 if lhs > rhs, -1 if lhs < rhs and 0 if lhs = rhs
private func compare(_ lhs: VersionNumber, _ rhs: VersionNumber) -> Int {
let lhsVersionComponents = lhs.version.components(separatedBy: ".").map { Int($0) ?? 0 }
let rhsVersionComponents = rhs.version.components(separatedBy: ".").map { Int($0) ?? 0 }
for i in 0..<max(lhsVersionComponents.count, rhsVersionComponents.count) {
let l = i >= lhsVersionComponents.count ? 0 : lhsVersionComponents[i]
let r = i >= rhsVersionComponents.count ? 0 : rhsVersionComponents[i]
let comparison = l - r
if comparison > 0 {
return 1
} else if comparison < 0 {
return -1
} // (else test next component)
}
return 0 // version numbers are equal
}
public func > (lhs: VersionNumber, rhs: VersionNumber) -> Bool {
return compare(lhs, rhs) == 1
}
public func < (lhs: VersionNumber, rhs: VersionNumber) -> Bool {
return compare(lhs, rhs) == -1
}
public func == (lhs: VersionNumber, rhs: VersionNumber) -> Bool {
return compare(lhs, rhs) == 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment