问题
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