Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Control Flow and Functions

Conditionals and switch

Learn Objective-C decision making with if, else if, switch, enums and string comparisons, including nil checks, fallthrough rules and clean multi-branch patterns.

Programs make decisions. Objective-C uses the same if, else and switch statements as C, with a few idioms that come from working with objects: checking for nil, comparing strings by content, and switching over enums. This lesson also covers guard-style early returns and the places where a switch cannot be used.

if and else

OBJECTIVEC
NSInteger score = 82;

if (score >= 90) {
    NSLog(@"Grade A");
} else if (score >= 80) {
    NSLog(@"Grade B");
} else {
    NSLog(@"Keep practicing");
}

The condition is any C expression: zero is false and everything else is true. Always use braces, even for one statement. A missing brace is the root of well-known security bugs and the compiler can warn about misleading indentation.

Conditions can combine with &&, || and !, and short-circuiting keeps guards safe:

OBJECTIVEC
if (user != nil && [user.name length] > 0) {
    NSLog(@"Hello, %@", user.name);
}

Testing objects

For objects, a bare pointer works as a condition: a non-nil pointer is true. Both forms below are common:

OBJECTIVEC
if (user) { ... }          // user is not nil
if (!user) { ... }         // user is nil
if (user == nil) { ... }   // explicit

Do not confuse this with content tests. An empty string is a non-nil object, so it is true. Check emptiness explicitly:

OBJECTIVEC
if (name.length == 0) { NSLog(@"empty or nil"); }   // works for nil too: length is 0

Because messages to nil return 0, name.length == 0 is true for both nil and @"".

Comparing values

OBJECTIVEC
if ([answer isEqualToString:@"yes"]) { ... }       // string content
if ([count isEqualToNumber:@3]) { ... }            // NSNumber
if (status == ABCStatusPublished) { ... }          // enum or int: ==

The strings may be nil: [nil isEqualToString:@"x"] returns NO, but [@"x" isEqualToString:nil] is also NO and safe, so the order is less dangerous than in Java.

The ternary operator

For simple choices that produce a value:

OBJECTIVEC
NSString *label = (count == 1) ? @"item" : @"items";

Do not nest ternaries more than once; use if instead.

Early returns

Deep nesting makes code hard to read. Check the failing cases first and return early:

OBJECTIVEC
- (void)sendMessage:(NSString *)text to:(User *)user {
    if (user == nil) { return; }
    if (text.length == 0) { return; }

    // the main path is not indented
    [user receive:text];
}

switch

switch compares one integer-like value against many constants:

OBJECTIVEC
switch (status) {
    case ABCStatusDraft:
        NSLog(@"draft");
        break;
    case ABCStatusPublished:
    case ABCStatusArchived:
        NSLog(@"visible or old");
        break;
    default:
        NSLog(@"unknown");
        break;
}

Key points:

  • The switched value must be an integer type, char or an enum. It cannot be an NSString, a floating-point number or any object.
  • Each case label must be a constant.
  • Execution falls through to the next case unless you write break. Stacked labels share one block, as above. A deliberate fall-through should be commented, and newer clang offers [[clang::fallthrough]].
  • Variables declared inside a case need their own braces: case 1: { int x = 5; ... break; }.
  • When switching over an NS_ENUM and listing every case, omit default. The compiler then warns when someone adds a new case and forgets to handle it here.

Switching on strings

There is no string switch. Use an if chain, or a dictionary that maps strings to enum values or blocks:

OBJECTIVEC
NSDictionary *lookup = @{ @"draft": @(ABCStatusDraft),
                          @"published": @(ABCStatusPublished) };
ABCStatus s = (ABCStatus)[lookup[input] integerValue];

Ranges

C has no range cases, but clang and GCC accept case 1 ... 5: as an extension. It is not portable; prefer if with >= and <= for ranges.

Stand-in: grading with if and switch

The control flow is the same in C. The first example uses if chains for ranges; the second uses switch with fall-through and an enum.

C Stand-in (C): if/else chains and early returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Stand-in (C): switch with an enum and fall-through

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Forgetting break, so extra cases run.
  • Using = in a condition instead of ==.
  • Comparing strings with ==.
  • Treating an empty NSString as false.
  • Declaring variables in a case without braces.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which type can you NOT use as the switch expression?

    switch needs an integer-like value. Strings must be compared with if and isEqualToString:.
  2. 2. What happens if you omit break at the end of a case?

    C-style switch falls through to the next label.
  3. 3. Is an empty NSString (@"") true in if (str)?

    The condition tests the pointer, not the content. Check str.length == 0 for emptiness.
  4. 4. Why leave out default when switching over every case of an NS_ENUM?

    Without default, the compiler can report missing enum cases.

Summary

  • if/else if/else use C truth rules: zero is false, everything else is true.
  • A non-nil object pointer is true; test emptiness with length or count.
  • Use isEqualToString: for strings and == for numbers and enums.
  • switch works on integer-like values and falls through without break.
  • Return early to avoid deep nesting.

Next: Loops and Fast Enumeration