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

前端 未结 7 2136
感情败类
感情败类 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:19

    If you wanted to do this with an object type, like say NSString, and you feel comfortable with categories, you could do add a category method:

    @implementation NSObject (IsEqualMultiple)
    
    - (BOOL)isEqualTo:(id)obj1 or:(id)obj2 
    {
        return [self isEqual:obj1] || [self isEqual:obj2];
    }
    
    @end
    

    Then you could use it like this:

    if ([string isEqualTo:@"hello" or:@"dolly"])
    

提交回复
热议问题