Ad

Our DNA is written in Swift
Jump

Radar: LLVM Enhancement: @switch

Since Apple is starting to enhance LLVM with new language elements I figure that it might be a good time to suggest them as well, of course via Radar.

This is an enhancement request for getting an object-oriented version of the classic C switch which would allow you to use objects – like NSString literals – for the cases.

Filed as rdar://14557382 and on Open Radar.

The classic C statement is useless for use in Objective-C if you want to use NSString literals as constants for the cases. This enhancement request is for adding an object-oriented version of the switch to Objective-C.

For example this could look like this:

define MyBarConstantValue @"bar"
 
NSString *string = @"foo";
@switch (string) {
   @"foo": 
      // statements
     break;
 
   MyBarConstantValue:    
      // statements
      break;
 
   default:
      break;
}

While a classic switch would do an == comparison between the expression and the labels this enhanced version would instead use isEqual: for the comparison. Otherwise the syntax would be identical.

Using this enhancement you could use any NSObject subclass which implements isEqual:. This would eliminate the need for creating enums for situations where an option is indeed an NSString. The above example currently has to be written:

if ([string isEqual:@"foo"]) {
   // statements
} else if ([string isEqual:MyBarConstantValue]) {
   // statements
} else {
   // statements
}

This is harder to parse than using the proposed @switch statement. Also this doesn’t allow for a “fall-through” for a few options by omitting the break statement. So this would also have to be smart to resolve this scenario.


Categories: Bug Reports

8 Comments »