Can Objective-C switch on NSString?

后端 未结 14 1132
不知归路
不知归路 2020-12-04 05:40

Is there a more intelligent way to rewrite this?

if ([cardName isEqualToString:@\"Six\"]) {
    [self setValue:6];
} else if ([cardName isEqualToString:@\"Se         


        
14条回答
  •  误落风尘
    2020-12-04 06:09

    BY FAR.. my FAVORITE "ObjC Add-On" is ObjectMatcher

    objswitch(someObject)
        objcase(@"one") { // Nesting works.
            objswitch(@"b")
                objcase(@"a") printf("one/a");
                objcase(@"b") printf("one/b");
                endswitch // Any code can go here, including break/continue/return.
        }
        objcase(@"two") printf("It's TWO.");  // Can omit braces.
        objcase(@"three",     // Can have multiple values in one case.
            nil,              // nil can be a "case" value.
            [self self],      // "Case" values don't have to be constants.
            @"tres", @"trois") { printf("It's a THREE."); }
        defaultcase printf("None of the above."); // Optional default must be at end.
    endswitch
    

    AND it works with non-strings, TOO... in loops, even!

    for (id ifNumericWhatIsIt in @[@99, @0, @"shnitzel"])
        objswitch(ifNumericWhatIsIt)
            objkind(NSNumber)  printf("It's a NUMBER.... "); 
            objswitch([ifNumericWhatIsIt stringValue])
                objcase(@"3")   printf("It's THREE.\n"); 
                objcase(@"99")  printf("It's NINETY-NINE.\n"); 
                defaultcase     printf("some other Number.\n");
           endswitch
        defaultcase printf("It's something else entirely.\n");
    endswitch
    
    It's a NUMBER.... It's NINETY-NINE.
    It's a NUMBER.... some other Number.
    It's something else entirely.
    

    Best of all, there are SO few {...}'s, :'s, and ()'s

提交回复
热议问题