Comparing version numbers

后端 未结 8 1600
予麋鹿
予麋鹿 2020-12-11 11:39

Some time ago, I read that comparing version numbers can be done using the following code snippet:

NSString *vesrion_1 = @\"1.2.1\";
NSString *version_2 = @\         


        
8条回答
  •  长情又很酷
    2020-12-11 12:10

    I'd say no, it's not safe. Version numbers are not really numbers but hierarchies of numbers. Consider for instance three version numbers:

    1.19
    1.3
    1.30
    

    A numeric comparison would put 1.19 as being smaller than 1.3 and 1.30. It would also say 1.3 and 1.30 are equal. If the above are version numbers, that is almost certainly not what you want.

    There's also the issue of localisation*. In French, the above would not even parse as numbers.

    It's far better to treat version numbers as what they are, a hierarchy of separate integers. You can easily chop them up with -componentsSeparatedByString:

    *Somewhat ironically, my browser is flagging the British English spelling of localisation as being incorrect.

提交回复
热议问题