Skip to content

Instantly share code, notes, and snippets.

@swillits
Last active April 12, 2018 20:37
Show Gist options
  • Save swillits/dfa1e7c7c540cc25fc9526d95d72cdcd to your computer and use it in GitHub Desktop.
Save swillits/dfa1e7c7c540cc25fc9526d95d72cdcd to your computer and use it in GitHub Desktop.
Convenient macOS/iOS/etc version checking at runtime
//
// OSVersion.swift
// Created by Seth Willits on 4/12/18.
//
// if runtimeOSVersion.isAtLeast(10, 12) { ... }
import Foundation
var runtimeOSVersion: OperatingSystemVersion {
return ProcessInfo.processInfo.operatingSystemVersion
}
extension OperatingSystemVersion: Comparable, Equatable {
init(_ major: Int, _ minor: Int, _ patch: Int) {
self.init(majorVersion: major, minorVersion: minor, patchVersion: patch)
}
func `is`(_ major: Int, _ minor: Int, _ patch: Int? = nil) -> Bool {
let v1 = (patch == nil) ? self.majorMinor : self
let v2 = OperatingSystemVersion(major, minor, patch ?? 0)
return v1 == v2
}
func isAtLeast(_ major: Int, _ minor: Int, _ patch: Int? = nil) -> Bool {
let v1 = (patch == nil) ? self.majorMinor : self
let v2 = OperatingSystemVersion(major, minor, patch ?? 0)
return v1 >= v2
}
func isAfter(_ major: Int, _ minor: Int, _ patch: Int? = nil) -> Bool {
let v1 = (patch == nil) ? self.majorMinor : self
let v2 = OperatingSystemVersion(major, minor, patch ?? 0)
return v1 > v2
}
func isBefore(_ major: Int, _ minor: Int, _ patch: Int? = nil) -> Bool {
let v1 = (patch == nil) ? self.majorMinor : self
let v2 = OperatingSystemVersion(major, minor, patch ?? 0)
return v1 < v2
}
public static func < (lhs: OperatingSystemVersion, rhs: OperatingSystemVersion) -> Bool {
return lhs.asUInt32 < rhs.asUInt32
}
public static func == (lhs: OperatingSystemVersion, rhs: OperatingSystemVersion) -> Bool {
return lhs.asUInt32 == rhs.asUInt32
}
private var majorMinor: OperatingSystemVersion {
return OperatingSystemVersion(majorVersion, minorVersion, 0)
}
private var asUInt32: UInt32 {
return ((0xFF & UInt32(majorVersion)) << 16) | ((0xFF & UInt32(minorVersion)) << 8) | ((0xFF & UInt32(patchVersion)))
}
}
@swillits
Copy link
Author

let v1 = OperatingSystemVersion(10, 1, 6)
let v2 = OperatingSystemVersion(10, 2, 4)
let v3 = OperatingSystemVersion(10, 2, 5)
let v4 = OperatingSystemVersion(10, 3, 1)

assert(v1 < v2)
assert(v2 < v3)
assert(v2 != v3)
assert(v3 > v2)
assert(v2 != v3)

assert(v1.is(10, 1))
assert(v1.is(10, 1, 6))
assert(!v1.is(10, 1, 7))

assert(v2.isAtLeast(10, 1))
assert(v2.isAtLeast(10, 1, 5))
assert(v2.isAtLeast(10, 2))
assert(v2.isAtLeast(10, 2, 1))
assert(v2.isAtLeast(10, 2, 4))
assert(!v2.isAtLeast(10, 3))
assert(!v2.isAtLeast(10, 3, 1))

assert(v2.isAfter(10, 1))
assert(v2.isAfter(10, 2, 3))
assert(!v2.isAfter(10, 2, 7))

assert(v2.isBefore(10, 3))
assert(v2.isBefore(10, 2, 9))
assert(!v2.isBefore(10, 2, 4))
assert(!v2.isBefore(10, 1, 4))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment