Is there a format specifier that works with Boolean values?

Viewed 14474

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.

7 Answers

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

As @MottiShneor pointed out, there is a more detailed list in the os_log(3) man pages:

Value type      Custom specifier         Example output
-----------------------------------------------------------------------------
BOOL            %{BOOL}d                 YES
bool            %{bool}d                 true
darwin.errno    %{darwin.errno}d         [32: Broken pipe]
darwin.mode     %{darwin.mode}d          drwxr-xr-x
darwin.signal   %{darwin.signal}d        [sigsegv: Segmentation Fault]
time_t          %{time_t}d               2016-01-12 19:41:37
timeval         %{timeval}.*P            2016-01-12 19:41:37.774236
timespec        %{timespec}.*P           2016-01-12 19:41:37.2382382823
bitrate         %{bitrate}d              123 kbps
iec-bitrate     %{iec-bitrate}d          118 Kibps
uuid_t          %{uuid_t}.16P            10742E39-0657-41F8-AB99-878C5EC2DCAA
sockaddr        %{network:sockaddr}.*P   fe80::f:86ff:fee9:5c16
in_addr         %{network:in_addr}d      127.0.0.1
in6_addr        %{network:in6_addr}.16P  fe80::f:86ff:fee9:5c16

On Swift, use String(describing: booleanValue)

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

Of course you can use the direct boolean formatting specifier %x

BOOL flag = YES;
NSLog(@"You got: %x", flag);

but at the very least, you can always rely on NSNumber objects, that 'remember' the 'type' of data they 'box' so this NSLog will also work fine:

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

Pay attention to the use of NSNumber literals - not strings.

Related