Duy Khanh Nguyen Duy Khanh Nguyen - 3 months ago 8
iOS Question

Using Enum and Switch on Objective-C

I have a view with 3 text fields:


  1. Current password

  2. New password

  3. Confirm new password



The requirement is, to check the validity of these passwords, if the conditions are not satisfied, there will be a alert view popup.


  1. If user inputs the wrong current password

  2. New password must have more than 8 letters

  3. the new passwords must match



I used
if
-
else
but it seems not to be suitable, and tried
switch
-
case
instead. But it still doesn't work.

My code:

NSString *textFromBox1 = [stringArray objectAtIndex:0];
NSString *textFromBox2 = [stringArray objectAtIndex:1];
NSString *textFromBox3 = [stringArray objectAtIndex:2];

enum ErrorCase{
oldPasswordCase,
newPasswordLength,
newPasswordCheck,
};

enum ErrorCase error;

if ([textFromBox1 length] < 2) {
error = oldPasswordCase;
} else if ([textFromBox2 length] < 8) {
error = newPasswordLength;
} else if (textFromBox2 != textFromBox3) {
error = newPasswordCheck;
}

switch (error) {
case oldPasswordCase:
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"過ち"
message:@"現在のパスワードが間違っています。"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
break;
case newPasswordLength:
{
UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:@"過ち"
message:@"パスワードを8文字以上で入力してください。"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert2 show];

}
break;
case newPasswordCheck:
{
UIAlertView *alert3 = [[UIAlertView alloc] initWithTitle:@"過ち"
message:@"新しいパスワードとパスワード(確認)が間違っています。"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert3 show];
}
break;

default:
break;
}


}

Answer

In Objective-C the argument in a switch statement must be an integer.

Use the NS_ENUM macro to declare the enum as integer

typedef NS_ENUM (NSInteger, ErrorCase) {
    oldPasswordCase,
    newPasswordLength,
    newPasswordCheck,
};

Then declare the error variable

ErrorCase error;

And as mentioned in Mateusz's answer you have to use isEqualToString to compare two strings.

Comments