Quicker if-statement: if `variable` is “value” or “value”

前端 未结 7 2121
感情败类
感情败类 2020-12-18 15:44

How can you compare against multiple possibilities in one argument?

Example:

if ((integer == 2) || (integer == 5))

if ((string == \"hello\") || (str         


        
7条回答
  •  悲哀的现实
    2020-12-18 16:08

    Actually, you can check if NSSet contains some object. This won't work with int, as it's not an object, but will work with NSString.

    I believe it could be written like this:

    if ( [[NSSet setWithObjects:@"hello", @"dolly", nil] containsObject:string] )
    

    So, if you want to compare ints, you should wrap them with NSNumber.

    This won't save a lot of code if you are not comparing tens of objects, but this looks pretty similar to what you want to get :)

    UPDATE:

    Or another way (quite similar to the answer from John Calsbeek, but works for multiple arguments):

    @implementation NSObject (IsEqualMultiple)
    
    - (BOOL)isEqualToOneOfObjects:(id)firstObject, ... {
        id eachObject;
        va_list argumentList;
    
        if (firstObject) {
            if ( [self isEqual:firstObject] ) return YES;
    
            va_start(argumentList, firstObject);
    
            while (eachObject = va_arg(argumentList, id))
                if ( [self isEqual:eachObject] ) return YES;
            va_end(argumentList);
        }
    
        return NO;
    }
    
    @end
    

    Usage:

    if ( [string isEqualToOneOfObjects:@"hello", @"dolly", @"this", @"is", @"Louis", nil] )
    

提交回复
热议问题