alan alan - 1 year ago 88
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 = @"";

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download