Created
May 20, 2016 12:26
-
-
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
This file contains 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
/** | |
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage