Ruub020
Ruub020

Reputation: 51

Objective-C If Or statement

Is there any way to use an if statement like this?

if ([number isEqualToString:@"1" 'or' @"2" 'or' @"3")] {

Is this 'or' possible and how would I do this?

Upvotes: 0

Views: 3539

Answers (3)

Anoop Vaidya
Anoop Vaidya

Reputation: 46533

I assume the variable number is of type string and you need to compare it with strings.

For this you can check it as:

NSString *number = @"2";

if ([@[@"1", @"2", @"3"] containsObject:number]) {
   NSLog(@"Contains");
}
else{
   NSLog(@"doesn't contain");
}

Upvotes: 1

juniperi
juniperi

Reputation: 3763

Not like that but you can create simple method to compare string to strings in array.

- (BOOL)arrayContainsEqualString:(NSString *)string array:(NSArray *)array {
    for(NSString *str in array) {
        if([str isEqualToString:string]) {
            return YES;
        }
    }
    return NO;
}

And calling that method

if([self arrayContainsEqualString:@"stringToCompare" array:@[@"str1", @"str2", @"str3"]]) ...

Upvotes: 2

Dinesh
Dinesh

Reputation: 939

if ([number isEqualToString:@"1"] || [number isEqualToString:@"2"] || [number isEqualToString:@"3"]) or if you have an NSArray of your string objects you can just check [NSArray containsObject:] to find if string actually contains in array.

Upvotes: 3

Related Questions