简体   繁体   中英

Ternary Operator in C (including Objective-C & C++) - Do Nothing on Else Condition

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?

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.

Code readability should be high on your list of considerations when writing code

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM