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?
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.
The statements in a switch continue to execute as long as the condition at the top of the switch remains true.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With