Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- struct VersionNumber {
- private let components: [UInt]
- var value: String {
- return components.map { "\($0)" }.joined(separator: ".")
- }
- init(string: String) {
- let split = string.split(separator: ".")
- let cast = split.compactMap { UInt($0) }
- if split.count == cast.count {
- components = cast
- } else {
- components = []
- }
- }
- }
- extension VersionNumber: Codable {
- init(from decoder: Decoder) throws {
- let container = try decoder.singleValueContainer()
- let string = try container.decode(String.self)
- self.init(string: string)
- }
- func encode(to encoder: Encoder) throws {
- var container = encoder.singleValueContainer()
- try container.encode(value)
- }
- }
- extension VersionNumber: Comparable {
- static func == (lhs: VersionNumber, rhs: VersionNumber) -> Bool {
- let lCount = lhs.components.count
- let rCount = rhs.components.count
- // Compare the components directly if they have the same count.
- if lCount == rCount { return lhs.components == rhs.components }
- // Compare the common components.
- for (l, r) in zip(lhs.components, rhs.components) {
- if l != r { return false }
- }
- // Return false if any component in the version with the greater amount of components is not zero.
- let (greater, lesserCount) = lCount > rCount ? (lhs.components, rCount) : (rhs.components, lCount)
- for c in greater[lesserCount..<greater.count] {
- if c != 0 { return false }
- }
- return true
- }
- static func < (lhs: VersionNumber, rhs: VersionNumber) -> Bool {
- let lCount = lhs.components.count
- let rCount = rhs.components.count
- for (l, r) in zip(lhs.components, rhs.components) {
- if l == r { continue }
- // Compare the first component which is not equal.
- return l < r
- }
- // The versions are equal if all the compared elements are the same and the components have the same count.
- if lCount == rCount { return false }
- // See if any of the components in the version with the greater amount of components is not zero.
- if lCount > rCount {
- for c in lhs.components[rCount..<lCount] {
- if c != 0 { return false }
- }
- } else {
- for c in rhs.components[lCount..<rCount] {
- if c != 0 { return true }
- }
- }
- // Any extra components are zero. The versions are equal.
- return false
- }
- }
Add Comment
Please, Sign In to add comment