Skip to content

Instantly share code, notes, and snippets.

@greggjaskiewicz
Last active December 8, 2018 17:40
Show Gist options
  • Save greggjaskiewicz/87c5192996df61adbf146c856f0d710e to your computer and use it in GitHub Desktop.
Save greggjaskiewicz/87c5192996df61adbf146c856f0d710e to your computer and use it in GitHub Desktop.
AppVersion object in Swift
//
// AppVersion.swift
//
// Created by Gregg Jaskiewicz on 08/12/2018.
// Copyright © 2018 Gregg Jaskiewicz Clear Prop Ltd. All rights reserved.
//
import Foundation
public struct AppVersion: Comparable {
let elements: [Int]
init(versionString: String) {
let strings = versionString.split(separator: ".")
let elements = strings.map { (s) -> Int in
let number = Int(s) ?? 0
return number
}
self.elements = elements
}
public static func == (lhs: AppVersion, rhs: AppVersion) -> Bool {
var lValue = lhs.elements
var rValue = rhs.elements
if lValue.count > rValue.count {
let zeros = Array(repeating: 0, count: lValue.count-rValue.count)
rValue.append(contentsOf: zeros)
}
if rValue.count > lValue.count {
let zeros = Array(repeating: 0, count: rValue.count-lValue.count)
lValue.append(contentsOf: zeros)
}
return lValue == rValue
}
public static func < (lhs: AppVersion, rhs: AppVersion) -> Bool {
var lValue = lhs.elements
var rValue = rhs.elements
if lValue.count > rValue.count {
let zeros = Array(repeating: 0, count: lValue.count-rValue.count)
rValue.append(contentsOf: zeros)
}
if rValue.count > lValue.count {
let zeros = Array(repeating: 0, count: rValue.count-lValue.count)
lValue.append(contentsOf: zeros)
}
// find out the biggest 10s
let both = lValue+rValue
let tens = both.map { (v) -> Int64 in
if v == 0 {
return 10
}
let f = Float(v)*10
let ten = (f)/(f/100)
return Int64(ten)
}
let tenMultiplier = tens.max() ?? 100
// create Int64s out of this
var l:Int64 = 0
var m = tenMultiplier
for(_, value) in lValue.reversed().enumerated() {
let element = m*Int64(value)
l = l+element
m = m*tenMultiplier
}
// create Int64s out of this
var r:Int64 = 0
m = tenMultiplier
for(_, value) in rValue.reversed().enumerated() {
let element = m*Int64(value)
r = r+element
m = m*tenMultiplier
}
return l < r
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment