alan alan - 6 months ago 40
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
is null, a value of
(the empty string:
) will be assigned. How do I achieve this in Objective-C? Is my only option:

someStringValue = @"";


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 : @""; })

Sample usage:

someStringValue = StringOrEmpty(someStringValue);