-1

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?

  • 3
    3.2.7 is not a number. You should save it as a string. Btw, you can compare string as well as compare a number. – Quoc Nguyen Dec 07 '18 at 07:57
  • 1
    It's like `version` number. Maybe you could divide it into `MAJOR`.`MINOR`.`PATCH` numbers with `struct` or `class`. – AechoLiu Dec 07 '18 at 08:08
  • @AechoLiu will try , thanks for the help – Dineshprabu S Dec 07 '18 at 08:35
  • You can consider saving it as an `IndexPath`. This type can be initialized with an int array (`IndexPath(indexes: [3,2,7])`) and it it already conforms to `Comparable`. – Lutz Dec 07 '18 at 10:00
  • @Lutz but I'm working in Objective C. IndexPath is in swift only.So, it doesn't – Dineshprabu S Dec 07 '18 at 10:34
  • @Dineshprabu It exists in Objective-C as well. It's called `NSIndexPath` and is also comparable `- (NSComparisonResult)compare:(NSIndexPath *)otherObject;` Initialization is a little less convenient, though. – Lutz Dec 07 '18 at 10:42
  • Unclear what "in Numbers" is supposed to mean. Please show actual input including object type, and desired output. – matt Dec 08 '18 at 03:23

2 Answers2

1

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
-1

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)