Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert iOS version string into number - Swift
// Why do you want a numeric version? Because number format is easier to use than string.
// For example, you may want to write a NSPredicate for Core Data fetch for different version:
// NSPredicate(format: "clientVersionNumber < %@", "2070500") // 2.7.5
// This gist assume the version digit is limitted to 4.
public static var versionString: String {
return (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String) ?? "1.0"
}
// Only support 4 digits, invalid string will return 0, longer digits will be dropped
// 3.2.2.1 -> 3020201, check testVersionNumber() for examples
public static func versionNumber(from version: String?) -> Int32 {
guard let version = version else {
return 0
}
var result = ""
let limitDigit: Int = 4
let versionSplit: [Int] = Array(version.split(separator: ".").map { Int($0) ?? 0 }.prefix(limitDigit))
let versionDigits: [Int] = versionSplit + Array(repeating: 0, count: max(limitDigit - versionSplit.count, 0))
assert(versionDigits.count == limitDigit)
let formatter = NumberFormatter()
formatter.maximumIntegerDigits = 2
formatter.minimumIntegerDigits = 2
versionDigits.forEach { d in
result.append(formatter.string(from: d as NSNumber) ?? "00")
}
return Int32(result) ?? 0
}
func testVersionNumber() throws {
XCTAssertEqual(BaseManagedObject.versionNumber(from: "2.1"), 2010000)
XCTAssertEqual(BaseManagedObject.versionNumber(from: "3.1.2"), 3010200)
XCTAssertEqual(BaseManagedObject.versionNumber(from: "3.2.2.1"), 3020201)
XCTAssertEqual(BaseManagedObject.versionNumber(from: "3.2.2.1.1"), 3020201)
XCTAssertNotEqual(BaseManagedObject.versionNumber(from: "3.2.2"), 3020201)
XCTAssertEqual(BaseManagedObject.versionNumber(from: "mess"), 0)
XCTAssertEqual(BaseManagedObject.versionNumber(from: ""), 0)
XCTAssertEqual(BaseManagedObject.versionNumber(from: nil), 0)
XCTAssertEqual(BaseManagedObject.versionNumber(from: "1"), 1000000)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment