Skip to content

Instantly share code, notes, and snippets.

@stephanecopin
Last active March 29, 2023 13:53
Show Gist options
  • Save stephanecopin/887448c4e955c2612508dd84545c9003 to your computer and use it in GitHub Desktop.
Save stephanecopin/887448c4e955c2612508dd84545c9003 to your computer and use it in GitHub Desktop.
A simple Semantic Version struct for Swift. Can be used to parse short app version and compare them easily.
struct Version {
let major: UInt
let minor: UInt
let patch: UInt?
init(major: UInt, minor: UInt = 0, patch: UInt? = nil) {
self.major = major
self.minor = minor
self.patch = patch
}
init?(versionString: String) {
let splitVersion = versionString.split(separator: ".")
switch splitVersion.count {
case 0:
return nil
case 1:
guard let major = UInt(splitVersion[0]) else {
return nil
}
self.init(major: major)
case 2:
guard
let major = UInt(splitVersion[0]),
let minor = UInt(splitVersion[1])
else {
return nil
}
self.init(major: major, minor: minor)
default:
guard
let major = UInt(splitVersion[0]),
let minor = UInt(splitVersion[1]),
let patch = UInt(splitVersion[2])
else {
return nil
}
self.init(major: major, minor: minor, patch: patch)
}
}
}
extension Version: CustomStringConvertible {
var description: String {
var description = "\(self.major).\(self.minor)"
if let patch {
description += ".\(patch)"
}
return description
}
}
extension Version: Equatable {
static func ==(lhs: Version, rhs: Version) -> Bool {
lhs.major == rhs.major && lhs.minor == rhs.minor && lhs.patch == rhs.patch
}
}
extension Version: Hashable {
func hash(into hasher: inout Hasher) {
major.hash(into: &hasher)
minor.hash(into: &hasher)
patch.hash(into: &hasher)
}
}
extension Version: Comparable {
static func <(lhs: Version, rhs: Version) -> Bool {
(
lhs.major,
lhs.minor,
lhs.patch ?? 0
) < (
rhs.major,
rhs.minor,
rhs.patch ?? 0
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment