20

I'm trying to achieve the equivalent of the following C# code:

someStringValue = someStringValue ?? string.Empty;

Where if someStringValue is null, a value of string.Empty (the empty string: "") will be assigned. How do I achieve this in Objective-C? Is my only option:

if(!someStringValue)
   someStringValue = @"";

Solution thanks to @Dave DeLong:

someStringValue = someStringValue ?: @"";
alan
  • 6,705
  • 9
  • 40
  • 70

2 Answers2

31

Simple, using ternary operator.

someStringValue = someStringValue ? someStringValue : @"";

Or if you want a macro, you can do that too.

#if !defined(StringOrEmpty)
    #define StringOrEmpty(A)  ({ __typeof__(A) __a = (A); __a ? __a : @""; })
#endif

Sample usage:

someStringValue = StringOrEmpty(someStringValue);
Eric
  • 6,965
  • 26
  • 32
  • 44
    ... or even just `someStringValue = someStringValue ?: @"";` – Dave DeLong Jan 05 '13 at 18:35
  • Thank you, Eric. This is what I was hoping for. @Dave DeLong, thank you as well for streamlining it, I ultimately went with your implementation. – alan Jan 05 '13 at 18:39
  • 1
    @DaveDeLong My experience was JavaScript has taught me to avoid apocryphal operators. Even if I know what it is, my teammates probably won't and I'd rather it be immediately obvious. That having been said, +1 for the awesome tip. I had been missing the old `a = b || c` notation and that's just what I've been looking for. – Eric Jan 05 '13 at 18:46
0

If someStringValue is a class variable, you could add this code to your .m file that owns the string

- (void)setSomeStringValue:(NSString *)newSomeStringValue
{
   if (!newSomeStringValue) newSomeStringValue = @"";
   _someStringValue = newSomeStringValue;
}
Undo
  • 25,519
  • 37
  • 106
  • 129