Dieblitzen Dieblitzen - 4 years ago 84
Swift Question

What do the & and | operators do? How are they different from && and ||? Swift

I've seen many instances where

are used, but I haven't understood what they are used for. I know what
mean, but I would like to know the difference between them and their single character counterparts. Also, it would be great if someone could show me examples of where
are used (in Swift 2 please). Thank you

Answer Source

See the Wikipedia page on Bitwise Operation and the Swift documentation for bitwise operators.

These are bitwise operators. & is bitwise AND and | is bitwise OR.

See these examples:

    0011 (decimal 3)
AND 0010 (decimal 2)
  = 0010 (decimal 2)

   0101 (decimal 5)
OR 0011 (decimal 3)
 = 0111 (decimal 7)

Source: Wikipedia

The uses of bitwise operators have been discussed before on StackOverflow:

A use of bitwise XOR (not in your question, but a cool logic gate anyway) that caught my eye (by @Vilx- here) (I don't know how it works, but the answer was accepted and up-voted 34 times):

Swapping two integer variables without an intermediary variable:

A = A^B // A is now XOR of A and B
B = A^B // B is now the original A
A = A^B // A is now the original B

If these don't help, the Wikipedia page I already linked to twice in this post has an Applications section, but they don't really apply to higher-level languages (unless for some reason you want to optimize your arithmetic to use only bitwise operations).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download