So, I had a similar issue some time back, we needed to be able to compare the installed version with cloud based information and do "things"
The first thing I did was built a concept of a "version", which is based on "major.minor.patch" and "build" properties.
This allowed the cloud to send us a structure which we could understand.
struct Version: Comparable, CustomStringConvertible {
let major: Int
let minor: Int
let patch: Int
let build: Int
init(major: Int, minor: Int, patch: Int, build: Int) {
self.major = major
self.minor = minor
self.patch = patch
self.build = build
}
init(from: String, build: String = "0") {
let buildNumber = Int(build) ?? 0
let parts = from.split(separator: ".")
let major = Int(parts[0]) ?? 0
var minor = 0
var patch = 0
if parts.count >= 2 {
minor = Int(parts[1]) ?? 0
}
if parts.count >= 3 {
patch = Int(parts[2]) ?? 0
}
self.init(major: major, minor: minor, patch: patch, build: buildNumber)
}
var description: String {
return String(format: "%02d.%02d.%02d build %02d", major, minor, patch, build)
}
static func <(lhs: Version, rhs: Version) -> Bool {
return lhs.description.compare(rhs.description, options: NSString.CompareOptions.numeric) == ComparisonResult.orderedAscending
}
static func ==(lhs: Version, rhs: Version) -> Bool {
return lhs.description.compare(rhs.description, options: NSString.CompareOptions.numeric) == ComparisonResult.orderedSame
}
}
Add in a simple extensions to get it from the app itself...
extension Version {
static var app: Version = {
let version = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
let build = Bundle.main.infoDictionary!["CFBundleVersion"] as! String
return Version(from: version, build: build)
}()
}
And then you can do things like
if Version.app == Version(from: "2.5.2") {
// And now do some stuff
}
Now, you will need to play around with this, as my needs might not be exactly the same as yours, but this is basically what I was able to use and it worked well, for my needs
But aren't you comparing 2 strings there? What if the user is in version 3.0.0
and I want all users with version 2.5.2
and below to clean cache? Can I do: if Version.app <= Version(from: "2.5.2") { }
?
This is one of those nice little features of Swift (actually ObjC ). Have a look at what NSString.CompareOptions.numeric
does for the comparison
For example...
let userVersion = Version(from: "3.0.0")
let targetVersion = Version(from: "2.5.2")
userVersion == targetVersion // 3.0.0 == 2.5.2 - false ✅
userVersion > targetVersion // 3.0.0 > 2.5.2 - true ✅
userVersion < targetVersion // 3.0.0 < 2.5.2 - false ✅
userVersion >= targetVersion // 3.0.0 >= 2.5.2 - true ✅
userVersion <= targetVersion // 3.0.0 <= 2.5.2 - false ✅