17

How would one go about writing a one line if statement in objective-c? Is there a proper style for this?

I know of the ternary operator used for assignment (int a = condition ? b : c) but say I wanted to call a method is if(condition){ [self methodCall]; } the recommended way of dealing with this in one line?

In addition are there any objc style guides out there? (Think comparable to this ruby style guide) Coming back to a language after a while of not touching it makes me want to rethink how I style my code.

4 Answers 4

60

Ternary if statement (if - else)

condition ? [self methodcall] : [self otherMethodCAll];

Single method call

if (condition) [self methodcall];
2
  • That's more an if-else scenario. Could I do that and only call one method?
    – erran
    Nov 5, 2012 at 23:17
  • Thanks for easy explanation Feb 9, 2016 at 9:08
13

The single-line ruby-style if and unless statements do not have an equivalent in Objective-C. You can either stick with blocks, or just call the method on the same line:

if (condition) {
    [self method];
}

or

if (condition)
    [self method];

or

if (condition) [self method];
5
  • That's what I suspected. Thanks.
    – erran
    Nov 5, 2012 at 23:24
  • Actually looks like you can shorten the ternary operator to condition ?: [self method]; which is what I ended up using.
    – erran
    Nov 6, 2012 at 0:19
  • 1
    Keep in mind that the ternary operator used in that way is not a common Objective-C idiom and reduces readability.
    – mopsled
    Nov 6, 2012 at 5:07
  • Good point, luckily as of now I'm the only one touching the code base for it. ;)
    – erran
    Nov 6, 2012 at 5:08
  • 2
    @ipwnstuff Even if you are the only one, you should do it well. Forget Ruby and use Obj-C. Actually in many coding standards an if without bracers is frowned upon (even in some Ruby coding standards!). Trying to reduce the number of lines is a beginner error. There is nothing bad with increased number of lines if it increases code readability. Thinks like ?: should be never used.
    – Sulthan
    May 11, 2013 at 19:21
3

You don't need brackets...

if(condition) [self methodCall];

That's as succinct as it gets.

0

Yes, the only way of doing a "one-line if statement" in Objective-C is to put an if statement and its body on the same line.

2
  • Why do you ask "is this the only way" if you know that it is?
    – zneak
    Nov 5, 2012 at 23:25
  • I'll clarify in my question. I was wondering if there was a way to use the ternary operator or a ruby like way to format a single line if statement.
    – erran
    Nov 5, 2012 at 23:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.