100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Conditionals in Objective-C

Learn how Objective-C branches program flow using if/else, the ternary operator, and switch statements, and how BOOL and nil interact with truthiness.

Control Flow & MethodsBeginner8 min readJul 10, 2026
Analogies

if, else if, and else

Objective-C inherits its conditional structure directly from C, so an if statement evaluates any expression that reduces to a scalar value: zero (or nil/NULL) is treated as false, and any nonzero value is treated as true. This means you can write if (someObject) to check for a non-nil pointer without an explicit comparison, though many teams prefer the more explicit if (someObject != nil) for readability in larger codebases.

🏏

Cricket analogy: It's like an umpire's binary decision on an lbw appeal: either the ball was going on to hit the stumps (true, out) or it wasn't (false, not out) — there's no in-between state, just like a scalar condition in C.

Because Objective-C's BOOL is typically a signed char (or the modern bool from stdbool.h on 64-bit runtimes), comparing BOOL values with == YES is a classic pitfall: if a BOOL is set from an expression that produces a value other than 0 or 1, the comparison can silently fail. The idiomatic style is to write if (isValid) or if (!isValid) rather than if (isValid == YES), treating the BOOL as the condition itself.

🏏

Cricket analogy: Trusting the third umpire's direct 'out' signal rather than re-checking it against a specific replay angle is like writing if (isOut) instead of if (isOut == YES) — you trust the boolean directly rather than over-specifying the comparison.

The ternary operator

The ternary operator condition ? valueIfTrue : valueIfFalse lets you assign a value based on a condition in a single expression, and Objective-C also supports the shorthand condition ?: valueIfFalse, which returns condition itself when it's truthy. This shorthand is especially handy for nil-coalescing patterns, such as NSString *name = userProvidedName ?: @"Guest";, which avoids repeating userProvidedName twice.

🏏

Cricket analogy: Setting a batting order with nextBatter = isOpenerOut ? reserveOpener : originalOpener; is exactly a ternary — one compact decision replacing a full if/else block, like a captain making a snap call at the toss.

switch statements

Objective-C's switch statement works on integer types (including enums, NSInteger, and unichar), and crucially does not support NSString or object comparisons directly — falling through to the next case unless you add a break is standard C behavior, and forgetting it is a common bug. A frequent, idiomatic use is switching over an NSInteger-backed enum like a UITableView section index or a custom typedef enum representing app state.

🏏

Cricket analogy: Switching on matchFormat (Test, ODI, T20) to decide the number of overs per innings is a natural switch statement, where forgetting break after the T20 case would wrongly fall through into ODI logic.

objectivec
typedef NS_ENUM(NSInteger, AppState) {
    AppStateLoading,
    AppStateReady,
    AppStateError
};

- (void)handleState:(AppState)state {
    switch (state) {
        case AppStateLoading:
            NSLog(@"Loading...");
            break;
        case AppStateReady:
            NSLog(@"Ready!");
            break;
        case AppStateError:
            NSLog(@"Something went wrong.");
            break;
        default:
            NSLog(@"Unknown state");
            break;
    }

    // Ternary example with nil-coalescing shorthand
    NSString *statusText = (state == AppStateReady) ? @"OK" : @"Not Ready";
    NSString *displayName = self.userName ?: @"Guest";
    NSLog(@"%@ - %@ (%@)", statusText, displayName, @(state));
}

Objective-C's switch statement cannot switch directly on NSString objects because switch requires an integer-compatible expression. Attempting switch (someNSString) is a compile error; use a chain of if/isEqualToString: calls or map strings to an enum first.

NS_ENUM and NS_OPTIONS (from <Foundation/NSObjCRuntime.h>) are the modern, type-safe way to declare enums for use in switch statements, giving you compiler warnings when a switch doesn't handle every case.

  • Any nonzero scalar (including a non-nil pointer) is treated as true in an if condition.
  • Prefer if (flag) / if (!flag) over if (flag == YES) to avoid BOOL comparison pitfalls.
  • The ternary operator cond ? a : b and its shorthand cond ?: b compress simple if/else logic into one expression.
  • a ?: b returns a itself when truthy, making it useful for default/fallback values.
  • switch works only on integer-compatible types (including NS_ENUM values), never directly on NSString.
  • Forgetting break causes fall-through into the next case, a common and dangerous bug.
  • NS_ENUM gives compiler warnings for unhandled switch cases, improving safety over plain enums.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#ObjectiveCStudyNotes#ConditionalsInObjectiveC#Conditionals#Objective#Else#Ternary#StudyNotes#SkillVeris#ExamPrep