I want to store a value something like 3.2.7 in Numbers in iOS, coz I want to compare the value with other.
Is there any data type is available? or any tricks?
anyone have a solution for this?
I want to store a value something like 3.2.7 in Numbers in iOS, coz I want to compare the value with other.
Is there any data type is available? or any tricks?
anyone have a solution for this?
This is almost certainly a duplicate of Compare version numbers in Objective-C.
As the accepted answer there tells you, strings like @"3.2.1"
and @"2.3.7"
are strings, not numbers — but they can be compared in the intuitively numeric way as version strings, by calling compare:options:
with the NSNumericSearch option.
And if that doesn't quite satisfy your needs, other answers provide many useful tweaks to the comparison algorithm.
If you wanted to implement something like that in Swift you could probably get away with something like the following:
struct Version: Comparable, Equatable {
static func == (lhs: Version, rhs: Version) -> Bool {
return lhs.maj == rhs.maj && lhs.min == rhs.min && lhs.patch == rhs.patch
}
static func < (lhs: Version, rhs: Version) -> Bool {
if lhs.maj < rhs.maj || lhs.min < rhs.min || lhs.patch < rhs.patch { return true }
return false
}
var maj: Int
var min: Int
var patch: Int
var formatted: String {
return "\(maj).\(min).\(patch)"
}
}
let v1 = Version(maj: 1, min: 2, patch: 2)
let v2 = Version(maj: 1, min: 2, patch: 2)
let v3 = Version(maj: 2, min: 2, patch: 2)
let v4 = Version(maj: 1, min: 3, patch: 2)
let v5 = Version(maj: 1, min: 2, patch: 3)
print (v1 == v2)
print (v1 == v3)
print (v1 > v2)
print (v1 > v3)
print (v1 > v4)
print (v1 > v5)
print (v3 > v4)
print (v3 > v5)
print (v1.formatted)
print (v2.formatted)
print (v3.formatted)
print (v4.formatted)
print (v5.formatted)