erran
erran

Reputation: 1320

Single line if statement Objective-c

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.

Upvotes: 17

Views: 32446

Answers (4)

flavian
flavian

Reputation: 28511

Ternary if statement (if - else)

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

Single method call

if (condition) [self methodcall];

Upvotes: 60

mopsled
mopsled

Reputation: 8505

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];

Upvotes: 13

Michael Frederick
Michael Frederick

Reputation: 16714

You don't need brackets...

if(condition) [self methodCall];

That's as succinct as it gets.

Upvotes: 3

zneak
zneak

Reputation: 138031

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.

Upvotes: 0

Related Questions