Guest User

Untitled

a guest
Nov 17th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. import Foundation
  2.  
  3. struct VersionNumber {
  4. private let components: [UInt]
  5.  
  6. var value: String {
  7. return components.map { "\($0)" }.joined(separator: ".")
  8. }
  9.  
  10. init(string: String) {
  11. let split = string.split(separator: ".")
  12. let cast = split.compactMap { UInt($0) }
  13. if split.count == cast.count {
  14. components = cast
  15. } else {
  16. components = []
  17. }
  18. }
  19. }
  20.  
  21. extension VersionNumber: Codable {
  22. init(from decoder: Decoder) throws {
  23. let container = try decoder.singleValueContainer()
  24. let string = try container.decode(String.self)
  25. self.init(string: string)
  26. }
  27.  
  28. func encode(to encoder: Encoder) throws {
  29. var container = encoder.singleValueContainer()
  30. try container.encode(value)
  31. }
  32. }
  33.  
  34. extension VersionNumber: Comparable {
  35. static func == (lhs: VersionNumber, rhs: VersionNumber) -> Bool {
  36. let lCount = lhs.components.count
  37. let rCount = rhs.components.count
  38.  
  39. // Compare the components directly if they have the same count.
  40. if lCount == rCount { return lhs.components == rhs.components }
  41.  
  42. // Compare the common components.
  43. for (l, r) in zip(lhs.components, rhs.components) {
  44. if l != r { return false }
  45. }
  46.  
  47. // Return false if any component in the version with the greater amount of components is not zero.
  48. let (greater, lesserCount) = lCount > rCount ? (lhs.components, rCount) : (rhs.components, lCount)
  49. for c in greater[lesserCount..<greater.count] {
  50. if c != 0 { return false }
  51. }
  52.  
  53. return true
  54. }
  55.  
  56. static func < (lhs: VersionNumber, rhs: VersionNumber) -> Bool {
  57. let lCount = lhs.components.count
  58. let rCount = rhs.components.count
  59.  
  60. for (l, r) in zip(lhs.components, rhs.components) {
  61. if l == r { continue }
  62. // Compare the first component which is not equal.
  63. return l < r
  64. }
  65.  
  66. // The versions are equal if all the compared elements are the same and the components have the same count.
  67. if lCount == rCount { return false }
  68.  
  69. // See if any of the components in the version with the greater amount of components is not zero.
  70. if lCount > rCount {
  71. for c in lhs.components[rCount..<lCount] {
  72. if c != 0 { return false }
  73. }
  74. } else {
  75. for c in rhs.components[lCount..<rCount] {
  76. if c != 0 { return true }
  77. }
  78. }
  79.  
  80. // Any extra components are zero. The versions are equal.
  81. return false
  82. }
  83. }
Add Comment
Please, Sign In to add comment