2

I'm getting an "expected expression" error in a switch statement on the first line of the code below in this NSString: NSString *emailTitle = @"some text";

break;
    case 4:
        // mail
        // Email Subject
        NSString *emailTitle = @"some text";
        // Email Content
        NSString *messageBody = @"http://www.example.com/";
        // To address
        NSArray *toRecipents = [NSArray arrayWithObject:@""];

        MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
        mc.mailComposeDelegate = self;
        [mc setSubject:emailTitle];
        [mc setMessageBody:messageBody isHTML:NO];
        [mc setToRecipients:toRecipents];

        // Present mail view controller on screen
        [self presentViewController:mc animated:YES completion:NULL];

        break;
    case 5:

Without this piece of email code the switch statement works fine.

thanks for any help

hanumanDev
  • 6,592
  • 11
  • 82
  • 146

1 Answers1

18

you can't declare a variable in a case statement, because the scope is ambiguous...

change to the below, where the scope is specified by the brackets {}

 case 4:
        {
            // mail
            // Email Subject
            NSString *emailTitle = @"some text";
            // Email Content
            NSString *messageBody = @"http://www.example.com/";
           // To address
            NSArray *toRecipents = [NSArray arrayWithObject:@""];

            MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
            mc.mailComposeDelegate = self;
            [mc setSubject:emailTitle];
            [mc setMessageBody:messageBody isHTML:NO];
            [mc setToRecipients:toRecipents];

            // Present mail view controller on screen
            [self presentViewController:mc animated:YES completion:NULL];
        }
        break;
    case 5:
Wain
  • 118,658
  • 15
  • 128
  • 151
Grady Player
  • 14,399
  • 2
  • 48
  • 76
  • Why is the scope ambiguous? Why wouldn't the scope be that it only exists inside that switch? – TJ Olsen Jul 07 '21 at 17:54
  • @TJOlsen maybe that isn't he best way to describe it, but because of the way it is implemented with jumps and labels all of the code spills into the normal flat context of the containing function... – Grady Player Jul 08 '21 at 14:24