the best way to implement readable switch case with strings in objective-c?

前端 未结 3 1312
野趣味
野趣味 2021-01-31 20:57

In other dynamic languages like ruby, javascript etc. you can do simply this:

switch(someString) {
    case \"foo\":
       //do something;
       break;
    cas         


        
3条回答
  •  -上瘾入骨i
    2021-01-31 21:43

    NSString * extension = [fileName pathExtension];
    NSString * directory = nil;
    
    NSUInteger index = [@[@"txt",@"png",@"caf",@"mp4"] indexOfObjectPassingTest:^
                        BOOL(id obj, NSUInteger idx, BOOL *stop)
    {
        return [obj isEqualToString:extension];
    }];
    
    switch (index)
    {
        case 0:
            directory = @"texts/";
            break;
        case 1:
            directory = @"images/";
            break;
        case 2:
            directory = @"sounds/";
            break;
        case 3:
            directory = @"videos/";
            break;
        default:
            @throw [NSException exceptionWithName:@"unkonwnFileFormat"
                                           reason:[NSString stringWithFormat:@"zip file contain nknown file format: %@",fileName]
                                         userInfo:nil];
            break;
    }
    

提交回复
热议问题