Sean Danzeiser
Sean Danzeiser

Reputation: 9243

Range? Logical Or? objective C

Beginner's question here:

If I'm writing an If statement that I want to pertain to range of values, specifically tags, is there an easier way to do it besides using the Logical OR?

if (tableView.tag == 1 || tableView.tag==2 || tableView.tag==3) { do something}

This doesn't look very efficient..

Upvotes: 0

Views: 239

Answers (3)

echristopherson
echristopherson

Reputation: 7074

You can use switch with fall-through, if the value you're testing is of an integral type:

switch(tableView.tag) {
    case 1:
    case 2:
    case 3:
        // do something
        break;
    case 4:
    case 5:
    case 6:
    case 7:
    case 8:
    case 9:
        // do something else
        break;
}

Upvotes: 0

CRD
CRD

Reputation: 53000

Depends on your definition of "easier"... For small numbers of comparisons efficiency isn't really a consideration; you can either test for the individual values, or if the values are contiguous do a >= and <= test. You can always use a macro, or inline function, to tidy things up if you like, e.g:

NS_INLINE BOOL inRange(lower, value, upper) { return (lower <= value) && (value <= upper); }

For large numbers of tests, or simply aesthetics, other methods include using bitmasks and arrays.

If you are testing for a small number, up to 32 or 64, of contiguous values then you can define bitmasks for the sets you wish to test against and do bitwise and operations. E.g.:

typedef enum { Sunday = 0, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } Day;

int WeekendSet = (1 << Sunday | 1 << Saturday);

if ( (1 << day) & WeekendSet ) // day is a weekend

For larger, but still not too large, sets you can use arrays. This is how the standard library isletter(), isdigit() etc. functions are sometimes defined. As a single byte character is at most 255 declaring static arrays of booleans with 256 elements works quite well. E.g.

static uint8 isADigit[] = { 0, 0, ..., 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, ... }; // 256 values, only 10 1's for position's '0' through '9'

if ( isADigit[myChar] ) // myChar is a digit

Upvotes: 1

K2xL
K2xL

Reputation: 10280

if (tableView.tag >= minRange && tableView.tag <= maxRange)
{
}

Upvotes: 4

Related Questions