Why does @YES give an "expected expression" error, but @(YES) compiles? [duplicate]
Asked Answered
T

2

5

Using XCode 4.4's Convert to Modern Objective C Syntax, my [NSNumber numberWithBool:YES] calls were converted to @(YES). I had some issue that I've now forgotten, and changed them myself to @YES, which is supposed to be the correct syntax.

However, doing so gives me the error:

Unexpected type name 'BOOL': expected expression

I know that there is an "expression" syntax but I don't see why I can't simply use @YES and @NO.

// Compiler error:
NSDictionary *userDefaultsDefaults = @{@"hasBeenLaunched": @YES};

// No error
NSDictionary *userDefaultsDefaults = @{@"hasBeenLaunched": @(YES)};

Why does @(YES) compile while @YES does not, and what I can do to remedy that?

Thaumatology answered 28/7, 2012 at 0:24 Comment(0)
F
10

Short answer:

Use @(YES) and @(NO)


Longer answer:

Have a look at this answer which explains that this is mostly appears to be an oversight on Apple's part.

A commenter on this answer also points out:

There is one small thing I'd like to warn about. Literal bools are also not supported because of this. However, a quick fix that I implemented was adding this to the beginning of one of my common headers (in an iOS project)

#ifndef __IPHONE_6_0 
#if __has_feature(objc_bool) 
#undef YES 
#undef NO 
#define YES __objc_yes 
#define NO __objc_no 
#endif 
#endif
Fishing answered 28/7, 2012 at 0:30 Comment(2)
I see. So I'm not crazy. Thanks for the heads up. I added that to my prefix and was able to use the non-parenthesis syntax, as desired.Thaumatology
Looks like this is fixed in Xcode 4.5 -- using basically that same code, judging by the LLVM docs.Bobbee
C
0

The new number literals (like @YES) in the Clang update are not fully implemented into XCode until 4.5.

Convincing answered 20/9, 2012 at 20:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.