alan alan - 2 months ago 9
Objective-C Question

Assign empty string only if variable is nil (ternary operator)

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 = @"";

Answer

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);