Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Solution thanks to @Dave DeLong:

someStringValue = someStringValue ?: @"";
like image 893
alan Avatar asked Jan 05 '13 18:01

alan


1 Answers

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);
like image 143
Eric Avatar answered Oct 17 '22 14:10

Eric