Reputation: 1446
Just wanted to get some clarification from you guys. I'm trying to figure out how to do nothing on the else condition of an instruction that uses a ternary operator in Objective-C. I started doing something like the following which seems to work perfectly fine but I'm just hoping there's no weird voodoo going on in the background.
(condition) ? [object method] : nil;
self.intNumber = (localIntNumber) ? localIntNumber : self.intNumber; // set intNumber to itself if localIntNumber doesn't exist
self.myObject = (newObject) ? newObject : self.myObject; // different from intNumber in that we're dealing with a Foundation object (can be nil) instead of a regular int
Any of the above kosher to do? Thoughts?
Upvotes: 0
Views: 721
Reputation: 3947
Both of these are acceptable, read the same way and are compiled the same way:
self.intNumber = (localIntNumber) ? localIntNumber : self.intNumber;
self.myObject = (newObject) ? newObject : self.myObject;
This is also acceptable, as indicated by @Cornelius:
self.intNumber = localIntNumber ?: self.intNumber;
self.myObject = newObject ?: self.myObject;
This way of using the ternary operator isn't very common, though. Remember, you're writing code for your future self (and maybe others), so anything unnecessarily cryptic should be avoided.
Thanks @trojanfoe for bringing this up.
If you're not having an else
condition, I'd strongly recommend one of these:
if (localIntNumber) {
self.intNumber = localIntNumber
}
if (newObject) {
self.myObject = newObject;
}
Assuming, of course, that you've already set self.intNumber
and self.myObject
to valid values previously as to obviate the need for the else
condition.
Upvotes: 2