Last active
December 8, 2018 17:40
-
-
Save greggjaskiewicz/87c5192996df61adbf146c856f0d710e to your computer and use it in GitHub Desktop.
AppVersion object in Swift
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
// | |
// 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