In Swift, the init(rawValue:)
system ensures that casting an Int
to an enum either results in a valid enum case or nil
.
There is no such safety in Objective-C, where an invalid enum member can be created by casting a non-member "rawValue".
typedef NS_ENUM(NSInteger, ExampleEnum) {
first = 0,
second,
third,
};
+ (NSString *)stringForCase:(ExampleEnum)enumCase {
switch (enumCase) {
case first: return @"first";
case second: return @"second";
case third: return @"third";
}
}
+ (void)testEnum {
ExampleEnum invalidCase = (ExampleEnum)3; // this "rawValue" is out of bounds
NSString *string = [self stringForCase:invalidCase]; // nil
}
When switching on an enum, the compiler will warn you if an enum case is not handled:
Enumeration value 'third' not handled in switch
But once all cases have been handled, there is no similar warning that a "default" case is still possible for invalid members of the enum.
What is the behavior in such a situation? The NSString method seems to return nil
, and no crash is observed. But there is no return
from that method. Is a return nil
generated automatically, and under what circumstances?
Note that code statements after the "exhaustive" switch do not result in the warning that would normally be generated:
Code will never be executed