1

i am using objective-c to develop ios applications

i found in the documentations that enum have default values like this : "1<<0"

i don't understand this default value example:

enum {
    UIDataDetectorTypePhoneNumber   = 1 << 0,
    UIDataDetectorTypeLink          = 1 << 1,
    UIDataDetectorTypeAddress       = 1 << 2,
    UIDataDetectorTypeCalendarEvent = 1 << 3,
    UIDataDetectorTypeNone          = 0,
    UIDataDetectorTypeAll           = NSUIntegerMax
};

so, what is the default value for each element in this enum ?

thanks

yasserislam
  • 154
  • 1
  • 2
  • 11

2 Answers2

4

That is an enum with bitwise values or bit flags. Each value is an binary value in which only one bit is set to 1 and all the others are set to 0. That way you can store in a value as much flags as bits of an integer number has.

The shift left operator '<<' is a displacement of bits to the left or to the most significant side of the binary number. It is the same that calculating a "* 2" (times two) operation.

For example in the enum you have send in your question, the first value, UIDataDetectorTypePhoneNumber, is 1. The second one, UIDataDetectorTypeLink, is 2 and the third one, UIDataDetectorTypeAddress, is 4.

You combine that values as flags to set some different bits in the same integer:

NSInteger fooIntValue = UIDataDetectorTypePhoneNumber | UIDataDetectorTypeLink;

As '|' operation is bitwise, the result will be a binary value ...0011, that is 3. And you are indicating that your variable fooIntValue has two flags set to true for two different properties.

Gabriel
  • 3,319
  • 1
  • 16
  • 21
2

This << sign is for shifting bits to the left (multiplying by 2).

1 << 0 equals 1 (0b00000001)
1 << 1 equals 2 (0b00000010)
1 << 2 equals 4 (0b00000100)

Usually, if you dont asign any values, compiler will define first value as 0, second as 1 and so on. You can alway assign values yourself if you prefer (assignment that you're refering to is usually used for bitmasks, where each bit in a byte or a word has it's own meaning).

Rok Jarc
  • 18,765
  • 9
  • 69
  • 124