Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Obj-C, how could I make a switch statement that will evaluate classes, rather than just numbers?

in Obj-C a switch can only evaluate numbers. I'd like to be able to use it to compare classes of objects, something like this, for instance:

switch (currentSubViewController.class) 
{
     case UITableViewController.class :
          <do stuff>
          break;
     case UICollectionViewController.class :
          <do stuff>
          break;
}

Is there any way to achieve this? I'd really like to be able to use a switch because it makes it so easy to read for different cases, and I can add more cases at any point in the future. Any ideas?

like image 669
TraxusIV Avatar asked May 19 '13 23:05

TraxusIV


People also ask

Can Switch case have multiple conditions?

A switch statement includes literal value or is expression based. A switch statement includes multiple cases that include code blocks to execute. A break keyword is used to stop the execution of case block. A switch case can be combined to execute same code block for multiple cases.

Which statement is true about the switch statement?

The statements in a switch continue to execute as long as the condition at the top of the switch remains true.


2 Answers

As described in this forum post you would be better off applying the Liskov Substitution Principle and put the <do stuff> logic in the actual class, and then call a method shared by a superclass all these classes inherit (or a protocol in Obj-C if you're planning to have this logic shared across totally different classes).

This encapsulates all the logic in each implementation/sub-class without a higher level class needing to worry about every single possible implementation you might have. This improves maintainability and is more common in Object Oriented Programming as opposed to plain old procedural programming.

like image 167
Aram Kocharyan Avatar answered Sep 22 '22 02:09

Aram Kocharyan


The switch statement only works with integer types. You need a big if-else block.

If you really want to force a switch statement then you could work out something using a fixed array of classes and base the switch off of the index position of the class you are checking. But for readability in the case statements, you would need to define a set of constants representing the index position of each class. That's a lot of work and code to maintain just to avoid and if-else block.

like image 43
rmaddy Avatar answered Sep 23 '22 02:09

rmaddy