What values should I use for iOS boolean states?

后端 未结 5 1511
执笔经年
执笔经年 2021-01-04 10:23

It appears that in iOS I have a number of options that seem to fit for boolean values:

YES
NO
TRUE
FALSE
true
false

Which ones should I use

5条回答
  •  长发绾君心
    2021-01-04 11:06

    Short answer: you should prefer YES and NO for setting foundation properties of type BOOL.

    For the long answer, let's first see where are these constants defined:

    • true and false are from stdbool.h; they are #define-d as 1 and 0
    • TRUE and FALSE are from CFBase.h; they are #define-d as 1 and 0
    • YES and NO are from NSObjCRuntime.h. This is where signed char is typedef-ed as BOOL, and its two values are #define-d as ((BOOL)1) and ((BOOL)0) or __objc_yes/__objc_no if objc_bool is supported.

    The foundation classes consistently use BOOL, which is a typedef for signed char, to represent its boolean properties. Since the first two pairs get converted to int constants, using them may result in warnings, though it would probably work correctly anyway. The YES and NO constants, however, are defined in the most compatible way for your compiler, regardless of its version. Therefore, I would recommend using YES and NO consistently throughout your code.

提交回复
热议问题