Last active
October 21, 2022 04:03
-
-
Save endy-s/3791fe5c856cccaabff331fd49356dbf to your computer and use it in GitHub Desktop.
Compare two String Versions
This file contains hidden or 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
extension String { | |
func getRawVersionString() -> String? { | |
return self.removePrefix("v") | |
.split(separator: "-") | |
.first?.toString() | |
} | |
// Modified from the DragonCherry extension - https://github.com/DragonCherry/VersionCompare | |
private func compare(toVersion targetVersion: String) -> ComparisonResult { | |
let versionDelimiter = "." | |
var result: ComparisonResult = .orderedSame | |
var versionComponents = components(separatedBy: versionDelimiter) | |
var targetComponents = targetVersion.components(separatedBy: versionDelimiter) | |
while versionComponents.count < targetComponents.count { | |
versionComponents.append("0") | |
} | |
while targetComponents.count < versionComponents.count { | |
targetComponents.append("0") | |
} | |
for (version, target) in zip(versionComponents, targetComponents) { | |
result = version.compare(target, options: .numeric) | |
if result != .orderedSame { | |
break | |
} | |
} | |
return result | |
} | |
func isVersion(equalTo targetVersion: String) -> Bool { return compare(toVersion: targetVersion) == .orderedSame } | |
func isVersion(greaterThan targetVersion: String) -> Bool { return compare(toVersion: targetVersion) == .orderedDescending } | |
func isVersion(greaterThanOrEqualTo targetVersion: String) -> Bool { return compare(toVersion: targetVersion) != .orderedAscending } | |
func isVersion(lessThan targetVersion: String) -> Bool { return compare(toVersion: targetVersion) == .orderedAscending } | |
func isVersion(lessThanOrEqualTo targetVersion: String) -> Bool { return compare(toVersion: targetVersion) != .orderedDescending } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment