Is there a format specifier that works with Boolean values?

后端 未结 6 1711
悲&欢浪女
悲&欢浪女 2021-02-12 14:17

I want to do something like this:

NSLog(@\"You got: %x\", booleanValue);

where x is the specifier. But I can\'t find one! I want to avoid:

相关标签:
6条回答
  • 2021-02-12 14:23

    For os_log use

    os_log("results in true/false: %{bool}d", myBool)
    os_log("results in YES/NO: %{BOOL}d", myBool)
    

    If you are on the latest OS, you can also use string interpolation. For more info look at Format Custom Values in Message Strings

    0 讨论(0)
  • 2021-02-12 14:28

    Here are two things that work:

    NSLog(@"You got: %@",booleanValue ? @"YES" : @"NO");
    

    or you can cast:

    NSLog(@"You got: %d", (int)booleanValue);
    

    Which will output 0 or 1

    0 讨论(0)
  • 2021-02-12 14:28

    There's no format specifier that I know of. You can do this:

    NSLog(@"You got: %@", (booleanValue ? @"YES" : @"NO"));
    

    Alternately, you could write a little function or macro using the logic above that takes a BOOL and returns the appropriate string. You can then use that function in your log statements.

    0 讨论(0)
  • 2021-02-12 14:38

    On Swift, use String(describing: booleanValue)

    For example: os_log("You got %@", log: .default, type: .debug, String(describing: booleanValue))

    0 讨论(0)
  • 2021-02-12 14:42

    You can cast it to an int and use %d:

    NSLog(@"You got: %d", (int)booleanValue);
    

    Or use something like this:

    NSLog(@"You got: %@", booleanValue ? @"YES" : @"NO");
    
    0 讨论(0)
  • 2021-02-12 14:44

    Yes

    Here is the code:

    NSLog(@"%hhd",BOOLvariable);
    

    Prints 1 for Yes and 0 for No. Worked for me.

    0 讨论(0)
提交回复
热议问题