Skip to content

Instantly share code, notes, and snippets.

@danielgalasko
Created May 20, 2016 12:26
Show Gist options
  • Save danielgalasko/bc009e2e6c11eec08d5386b26dc83201 to your computer and use it in GitHub Desktop.
Save danielgalasko/bc009e2e6c11eec08d5386b26dc83201 to your computer and use it in GitHub Desktop.
A clean representation of a semantic version number in swift so you can compare version numbers as if they were numbers
/**
Represents a semantic version number in the form X.Y.Z
Its most useful feature is that it implements `Comparable`
making for easy comparison checks.
*/
struct VersionNumber {
let version: String
init(version: String) {
self.version = version.ensureSemanticallyCorrect()
}
func compare(version: VersionNumber) -> NSComparisonResult {
return self.version.compare(version.version)
}
}
func <(lhs: VersionNumber, rhs: VersionNumber) -> Bool {
return lhs.version.compare(rhs.version) == .OrderedAscending
}
func ==(lhs: VersionNumber, rhs: VersionNumber) -> Bool {
return lhs.version.compare(rhs.version) == .OrderedSame
}
extension VersionNumber: Comparable {
}
extension String {
/// make sure that we always have a semantic version in the form X.Y.Z
func ensureSemanticallyCorrect() -> String {
var comps = self
for _ in componentsSeparatedByString(".").count..<3 {
comps += ".0"
}
return comps
}
}
extension VersionNumber: CustomStringConvertible {
var description: String {
return self.version
}
}
@danielgalasko
Copy link
Author

usage

let upgradingToVersion = VersionNumber(version: "1.2.0")
let upgradingFromVersion = VersionNumber(version: "1.1.0")
if upgradingFromVersion < upgradingToVersion {
    //1.1.0 is less than 1.2.0 so our code will enter here
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment