Skip to content

Instantly share code, notes, and snippets.

@X140Yu
Created November 29, 2018 07:25
Show Gist options
  • Save X140Yu/2cf292e3735a5edf3d718fadbba9b5b1 to your computer and use it in GitHub Desktop.
Save X140Yu/2cf292e3735a5edf3d718fadbba9b5b1 to your computer and use it in GitHub Desktop.
compare string version in Swift
struct Version {
let rawValue: String
init(_ string: String) {
self.rawValue = string
}
enum CompareResult {
case greaterThan
case equal
case lessThan
}
func compareWithVersion(version: Version) -> CompareResult {
var v1 = rawValue.split(separator: ".").map { Int($0) ?? 0 }
var v2 = version.rawValue.split(separator: ".").map { Int($0) ?? 0 }
for i in 0..<max(v1.count, v2.count) {
let left = i >= v1.count ? 0 : v1[i]
let right = i >= v2.count ? 0 : v2[i]
if left > right {
return .greaterThan
} else if right > left {
return .lessThan
}
}
return .equal
}
static func ==(lhs: Version, rhs: Version) -> Bool {
return lhs.compareWithVersion(version: rhs) == .equal
}
static func <(lhs: Version, rhs: Version) -> Bool {
return lhs.compareWithVersion(version: rhs) == .lessThan
}
static func >(lhs: Version, rhs: Version) -> Bool {
return lhs.compareWithVersion(version: rhs) == .greaterThan
}
static func >=(lhs: Version, rhs: Version) -> Bool {
return lhs.compareWithVersion(version: rhs) == .greaterThan || lhs.compareWithVersion(version: rhs) == .equal
}
static func <=(lhs: Version, rhs: Version) -> Bool {
return lhs.compareWithVersion(version: rhs) == .lessThan || lhs.compareWithVersion(version: rhs) == .equal
}
}
Version("1.0") < Version("1.0.0")
Version("1.0") <= Version("1.0.0")
Version("1.1") > Version("1.2.0")
Version("1.2.1") > Version("1.2.1")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment