Switching on Objects in Objective-C

Objective-C's switch statements only work on primitive types that are constant at compile time. However, many Objective-C APIs expect the developer to determine their behaviour based on identifiers passed in as NSString. This leads to many if ([identifier isEqualToSting:@"stringA"]) {...} else if ([identifier isEqual... blocks in code to deal with, for example, KVO or -prepareForSegue:sender:.

To deal with this, HCObjectSwitch adds a simple syntax that is very similar to the native switch statement. In order to avoid clashing with the native syntax, all keywords start with a capital letter.

HCObjectSwitch

Overview

A simple way to implement object based switch-like statements in Objective-C using blocks. Any object that conforms to NSCopying can be used to switched on.

Example

id inVariable = /* ... */;
__block id outVariable;

Switch (segue.identifier)
{
    Case (@"EmbedLoginViewController")
    {
        self.loginViewController = segue.destinationViewController;
        outVariable = @"Embed";

        FallThroughToDefault();
    }, // each case statement needs to be wrapped in parenthesees and terminated with a comma

    Case (@"ShowSettingsViewController")
    {
        HCSettingsViewController *settingsViewController = segue.destinationViewController;
        settingsViewController.delegate = self;
        settingsViewController.title = inVariable;

        outVariable = @"Show";

        FallThroughToDefault();
    },

    Default
    {
        // The _object_ object is the object that was used in the switch statement.
        // This is available automatically.
        NSLog(@"Segue '%@' triggered by: %@", _object_, sender);
    },
}; // The ; is required

Usage

The syntaxt for HCObjectSwitch is very close to the standard switch statement. All keywords start with a capital letter.

  • Switch (object) Starts a switch clause on object
  • Case (option) Code executed if the object matches option. This is implemented through blocks under the hood, thus when writing to variables in the enclosing scope they need to be __block.
  • Default Code executed in the default case
  • FallthroughTo(option) Fall through to the option case. Cases can be skipped.
  • FallThroughToDefault Fall through to the default case. Cases can be skipped.

Parentheses after the Switch and Case statements are required, as is the comma at the end of the parenthesis.

comments powered by Disqus