C if vs switch

This question already has an answer here:

  • Why can't variables be declared in a switch statement? 23 answers

  • You need a separate scope in the case if you want to declare any variables there:

    switch ((int)typeOfHall) {
        case 1:
        {   /* Introduce a scope ... */
            NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Game"]; 
            NSPredicate *p = [NSPredicate predicateWithFormat:@"player_id == %@ ",[[NSUserDefaults standardUserDefaults] valueForKey:@"LoggedUserId"]];
            request.predicate = p;
            break;
        }   /* ... that ends here. */
        default:
            break;
    
    }
    

    Side note: if LocalHall is an enum value, your code is more readable without the cast:

    switch (typeOfHall) {
        case LocalHall:
        // ...
    
    链接地址: http://www.djcxy.com/p/14796.html

    上一篇: 初始化switch语句中的变量(int32)

    下一篇: C如果与切换