8

stringWithFormat should return a string, why does this statement not compile

NSAssert(YES, [NSString stringWithFormat:@"%@",@"test if compiles"]);

when

NSAssert(YES, @"test if compiles");

compiles?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
bogen
  • 9,954
  • 9
  • 50
  • 89
  • stringWithFormat with just a string again as a parameter in its format is redundant. I don't know exactly, but I believe, that Apple might have made some compiler level check on any such codes occurring. What error/message do you get when the assert doesn't compile ? – CodenameLambda1 Aug 23 '13 at 11:07
  • Extraneous closing brace – bogen Aug 23 '13 at 11:12

2 Answers2

18

Use this as :

NSAssert(YES, ([NSString stringWithFormat:@"%@",@"test if compiles"])); // Pass it in brackets ()

Hope it helps you.

Nishant Tyagi
  • 9,893
  • 3
  • 40
  • 61
15

You don't actually need to use stringWithFormat at all. NSAssert already expects you to pass a format string and variable arguments for formatting. Given your example, you'll find this works just as well:

NSAssert(YES, "%@", @"test if compiles");

Or, a more realistic example:

NSAssert(i > 0, @"i was negative: %d", i); 

The reason for your problem is because NSAssert is a macro, defined like this:

#define NSAssert(condition, desc, ...)

And the compiler is confused because there's ambiguity between the parameter list for stringWithFormat and that of the macro itself. As Nishant points out, you can add brackets to avoid the confusion if you really want to use stringWithFormat here.

Matt Gibson
  • 37,886
  • 9
  • 99
  • 128