Learn the Objective-C Switch Statement

Source

(c) 2013 kevin languedoc (klanguedoc)

Objective-C, the main programming language for Apple’s OS X and iOS operating systems and platforms, provides constructs for flow control. Flow control is a mechanism that provides programming languages a certain amount of decision making capabilities. Objective-C has two flow control constructs: the switch statement and the if...else...elseif statement. This tutorial will explain the switch statement, its syntax, where and when it is appropriate to use instead of the if...else...elseif statement and also provides examples on the different implementations or function models.

The switch statement in Objective-C is the same as the switch statement in the C programming, so knowing one will naturally allow you, the developer, to use your knowledge with the other language, especially since Objective-C is a superset of the C programming language and C is natively supported. Every programming language has a switch statement as was invented by Stephen Kleene in 1952 and published in his Introduction to Metamethematics. However the switch statement is not implemented in the same way across all languages, there are even variations amongst C based languages.

General Syntax

The switch statement uses a tree/branches design to evaluate numerical values and to return a 1 if the boolean expression being evaluated returns TRUE, otherwise returns -1 is the numerical expression is FALSE, meaning that no branch expression exists that matches the expression under evaluation, at which time, the routine can be directed to the default branch. As each branch expression is evaluated with the expression n, if a match is found, the flow then enters this branch and performs the desired computational and functional requirements and executes the break statement thus halting any further useless evaluations. The code sample below depicts a standard syntactic implementation.

int n = numerical expression to be evaluated
switch(n)
	case value1
		break;
	case value2
		break;
	case value_nth
		break;
	default

Objective-C Syntax and Examples

The switch statement in Objective-C begins with the “switch” keyword and includes an argument as an expression of type int. You can only evaluate a value of the int data type. The switch expressions defined in the branches are enclosed in curly braces. Each expression to be matched begins with the case keyword and finishes with a colon “:”. The Case expression to be evaluated is terminated or demarcated by the break keyword which is followed by the semi-colon “;”. In between are the statements to be executed. If no match can be found, the switch statement evaluation enters the default branch that can contain any number of logical statements to be executed.

switch (expression)

 {
     case equalledValue1:

          statements

          break;

     case equalledValue2:

          statements

          break;

     default:

          statements

          break;

 }

Another way to use the switch statement is to use an enum as follows:

enum label
{
	VALUE1 = 1,
	VALUE2 = 2,
	VALUE3 = 3,

};

switch(label)
{
	case VALUE1:
	//statements to be executed
	break;
case VALUE1:
	//statements to be executed
	break;
case VALUE1:
	//statements to be executed
	break;
default:
};

Test Project

To test the switch statement in a real situation create an iOS Single-View Application project. Open the storyboard and add a button and label and create an IBOutlet for the UILabel and IBAction for the button. To create the IBOutlet and IBAction, open the header file by clicking on the Editor assistant and ctrl+drag a connection from each UIControl, naming each in turn. To create the IBAction, you will need to change the connection type from the IBOutlet default to IBAction. Also add an int variable, enclosed in curly braces, named check. See the header code listing below. This will be used to evaluate the current integer value when the button is clicked.

SwitchIt - ViewController.h

//
//  ViewController.h
//  SwitchIt
//
//  Created by Kevin Languedoc on 1/1/13.
//  Copyright (c) 2013 Kevin Languedoc. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
    int check;
}
@property (strong, nonatomic) IBOutlet UILabel *outletTxt;
- (IBAction)actionBtn:(id)sender;

@end

Then close the Editor assistant and open the implementation file by clicking on the file in the project explorer. Locate the IBAction method that was created in the previous step and add the following code in the body:

SwitchIt - IBAction Implementation (ViewController.m)

- (IBAction)actionBtn:(id)sender {
    
    
    switch (check) {
        case 1:
            [self outletTxt].text=@"One was set";
            check ++;
            break;
        case 2:
            [self outletTxt].text=@"Two was set";
            check ++;
            break;
        case 3:
            [self outletTxt].text=@"Three was set";
            check ++;
            break;
        default:
            [self outletTxt].text=[NSString stringWithFormat:@"The number is %d",check];
            check ++;

            break;
    }
}

SwitchIt - Initialize the Check Variable

To initialize the int check variable, set the variable to 0 in the viewDidLoad method so that it gets initialized when the app is first loaded. As the button is click, the check variable gets incremented. When the value exceeds 3 the switch statement falls into the default statement. When the button is first clicked the value of heck is 0 so the switch statement goes to the default since the first case expression is 1.

SwitchIt - viewdidLoad check Initialization

- (void)viewDidLoad
{
    [super viewDidLoad];
	check=0;
}

The switch statement is very effective for long flow control code blocks instead of using if...else...elseif statement. However on the down side you can only evaluate int values. Compile and run the app or play the enclosed video to see the switch statement in action.

The switch statement is a powerful construct for flow management. But it has its limitations like not being able to evaluate non numerical values.

More by this Author


Comments 2 comments

Pawan Rai 2 years ago

why you defined a outlet as strong

"@property (strong, nonatomic) IBOutlet UILabel *outletTxt;"

any particular reason?


klanguedoc profile image

klanguedoc 2 years ago from Canada Author

Using strong means that you own and control the property. The compiler won't destroy the object until you decide to do so.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working