Using the switch statement in Obj-C

The following is a Switch / Case statement that displays an error message when the message cannot be sent. For the most part, everything seems to be correct, but when I put the UIAlertView in a switch statement, I get an error in Xcode:

Xcode error

 switch (result) { case MFMailComposeResultCancelled: NSLog(@"Result: Mail sending canceled"); break; case MFMailComposeResultFailed: NSLog(@"Result: Mail sending failed"); UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Sending Failed" message:@"The email could not be sent." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [message show]; break; default: NSLog(@"Result: Mail not sent"); break; } 

Why does it generate an error when I put the code inside the case ?

+6
source share
2 answers

Put it in brackets:

 case MFMailComposeResultFailed: { NSLog(@"Result: Mail sending failed"); UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Sending Failed" message:@"The email could not be sent." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [message show]; break; } 
+14
source

The problem is declaring variables inside switch cases. The compiler is upset that it tries to determine the scope when only part of the code is executed. If you put brackets around the contents of the "crash", this should be OK, as this limits the scope.

+12
source

Source: https://habr.com/ru/post/912055/


All Articles