Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short way to write conditional assignment in ObjC

Tags:

objective-c

Does Objective-C have an even shorter way of writing this line of code?

 a = b ? b : c;

That is, a way to say, a is equal to b as long it is not nil, else c. This is like Ruby's operator ||=

like image 947
Greg Avatar asked Mar 29 '11 11:03

Greg


2 Answers

Does the following work for you:

a = b ? : c;

(This syntax is a GNU extension to C, so you might have to use the GCC and not LLVM - http://gcc.gnu.org/onlinedocs/gcc-3.2.3/gcc/Conditionals.html#Conditionals).

like image 146
Joubert Nel Avatar answered Oct 23 '22 21:10

Joubert Nel


That's as short as you can get it in Objective-C! That's a nice little test you have there.

The only other short way I could come up with is as follows (I wouldn't recommend it for readability reasons and it isn't as short as yours!):

if (b) a = b; else a = c;
like image 22
James Bedford Avatar answered Oct 23 '22 21:10

James Bedford