Is there a format specifier that works with Boolean values?

匆匆过客 提交于 2020-01-12 06:38:10

问题


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:

if (booleanValue) {
    NSLog(@"You got: YES");
}
else {
    NSLog(@"You got: NO");
}

Any ideas? The docs didn't have a Boolean specifier. %@ didn't work either.


回答1:


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




回答2:


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");



回答3:


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.




回答4:


Yes

Here is the code:

NSLog(@"%hhd",BOOLvariable);

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




回答5:


On Swift, use String(describing: booleanValue)

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



来源:https://stackoverflow.com/questions/6752082/is-there-a-format-specifier-that-works-with-boolean-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!