Latest web development tutorials

# Swift Operators

An operator is a symbol, used to tell the compiler to perform a mathematical or logical operations.

Swift provides the following operators:

• Arithmetic operators
• Comparison
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Interval Operators
• Other operators

This chapter we will explain to you arithmetic operators, relational operators, logical operators, bitwise operators, assignment operator and other operators.

## Arithmetic operators

The following table lists the Swift language support arithmetic operators, 10 of which variable A variable B 20:

Operators description Examples
+ plus Results for A + B 30
- Minus A - B results -10
* Multiplication sign A * B results for 200
/ Sign of division B / A 2 results
% Remainder B% A result is 0
++ Increment A ++ 11 results
- Decrement A-- result 9

### Examples

Following is a simple example of arithmetic operations:

```import Cocoa

var A = 10
var B = 20

print("A + B 结果为：\(A + B)")
print("A - B 结果为：\(A - B)")
print("A * B 结果为：\(A * B)")
print("B / A 结果为：\(B / A)")
A++
print("A++ 后 A 的值为 \(A)")
B--
print("B-- 后 B 的值为 \(B)")
```

The above program execution results:

```A + B 结果为：30
A - B 结果为：-10
A * B 结果为：200
B / A 结果为：2
A++ 后 A 的值为 11
B-- 后 B 的值为 19
```

## Comparison

The following table lists the comparison operators Swift language support, wherein the variables A 10, B 20 variables:

Operators description Examples
== equal (A == B) is false.
! = not equal to (A! = B) is true.
> more than the (A> B) is false.
< Less than (A <B) is true.
> = greater or equal to (A> = B) is false.
<= Less than or equal (A <= B) is true.

### Examples

Following is a simple example of comparison operations:

```import Cocoa

var A = 10
var B = 20

print("A == B 结果为：\(A == B)")
print("A != B 结果为：\(A != B)")
print("A > B 结果为：\(A > B)")
print("A < B 结果为：\(A < B)")
print("A >= B 结果为：\(A >= B)")
print("A <= B 结果为：\(A <= B)")
```

The above program execution results:

```A == B 结果为：false
A != B 结果为：true
A > B 结果为：false
A < B 结果为：true
A >= B 结果为：false
A <= B 结果为：true
```

## Logical Operators

The following table lists the Swift language support logical operators, where the variable A is true, the variable B is false:

Operators description Examples
&& Logic and. If the operator is TRUE both sides was TRUE. (A && B) is false.
|| Or logic. If the operator on both sides of at least one of TRUE was TRUE. (A || B) is true.
! Logical NOT. It inverts the Boolean value, so true becomes false, false becomes true. ! (A && B) is true.

Following is a simple example of the logic operation:

```import Cocoa

var A = true
var B = false

print("A && B 结果为：\(A && B)")
print("A || B 结果为：\(A || B)")
print("!A 结果为：\(!A)")
print("!B 结果为：\(!B)")
```

The above program execution results:

```A && B 结果为：false
A || B 结果为：true
!A 结果为：false
!B 结果为：true
```

## Bitwise Operators

Bitwise Operators bits used to operate, ~, &, |, ^ were negated, and the bit, or by bit and, bitwise XOR operation with the following table examples:

p q p & q p | q p ^ q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

If A = 60; and B = 13; two variables corresponding to binary is:

```A = 0011 1100

B = 0000 1101
```

For bit operations:

Operators description Diagram Examples
& Bitwise and. With a bitwise AND operator to operate two numbers and then returns a new number, each bit of this number requires two input numbers are only 1 to 1. (A & B) result is 12, the binary is 0000 1100
| Bitwise or. Bitwise OR operator | compare two numbers and then returns a new number every set this number is the same conditions as the first one of the two input numbers are different from zero (that is, any one of 1, or are 1). (A | B) the result is 61, the binary is 00111101
^ Bitwise XOR bitwise exclusive OR operator ^ compare two numbers and then returns a number, this number is set to each bit Condition 1 are two inputs with a different number if equal to zero. (A ^ B) results for 49 binaries to 00,110,001
~ Bitwise operators - for a number of operations each bit inverted. (~ A) -61 result, the binary is 1100 0011 in 2's complement form.
<< Bitwise left. The left shift operator (<<) will move to the left all the bits number of bits specified operand.

The following figure shows << 1 11111111 (11111111 left one) results. Blue numerals being moved bit gray discarded bits, filling vacancies with orange 0.

A << 2 results for 240 binary is 11110000
>> Bitwise right. All the bits to the right and move the number of bits specified operator (<<) operand.

The following figure shows >> 1 11111111 (11111111 right one) results. Blue numerals being moved bit gray discarded bits, filling vacancies with orange 0.

A >> 2 results for 15 0000 1111 binary system

The following is a simple example of bit operations:

```import Cocoa

var A = 60  // 二进制为 0011 1100
var B = 13 // 二进制为 0000 1101

print("A&B 结果为：\(A&B)")
print("A|B 结果为：\(A|B)")
print("A^B 结果为：\(A^B)")
print("~A 结果为：\(~A)")
```

The above program execution results:

```A&B 结果为：12
A|B 结果为：61
A^B 结果为：49
~A 结果为：-61
```

## Assignment Operators

The following table lists the basic assignment operator Swift language:

Operators description Examples
= Simple assignment operator, specifies the right operand assigned to the left operand. C = A + B A + B operation result is assigned to C
+ = Adding after the assignment, the left and right sides of the operand before adding assigned to the left operand. C + = A corresponds to C = C + A
- = After subtraction assignment, the left and right operands on both sides of the left operand after subtraction assigned to. C - = A corresponds to C = C - A
* = Then multiplying the assignment, the left and right sides of the operands are multiplied before assignment to the left operand. C * = A corresponds to C = C * A
/ = Divided after the assignment, the left and right sides of the dividing operand after assignment to the left operand. C / = A is equivalent C = C / A
% = Remainder after the assignment, the left and right sides of the remainder operand after assignment to the left operand. C% = A is equivalent to C = C% A
<< = Bitwise left after assignment C << = 2 corresponds to C = C << 2
>> = Bitwise right after the assignment C >> = 2 is equivalent to C = C >> 2
& = Bitwise AND assignment after operation C & = 2 is equivalent to C = C & 2
^ = Bitwise exclusive OR operator and then assigned C ^ = 2 is equivalent to C = C ^ 2
| = Bitwise OR assignment after C | = 2 corresponds to C = C | 2

Following is a simple example of the assignment operator:

```import Cocoa

var A = 10
var B = 20
var C = 100

C = A + B
print("C 结果为：\(C)")

C += A
print("C 结果为：\(C)")

C -= A
print("C 结果为：\(C)")

C *= A
print("C 结果为：\(C)")

C /= A
print("C 结果为：\(C)")

//以下测试已注释，可去掉注释测试每个实例
/*
C %= A
print("C 结果为：\(C)")

C <<= A
print("C 结果为：\(C)")

C >>= A
print("C 结果为：\(C)")

C &= A
print("C 结果为：\(C)")

C ^= A
print("C 结果为：\(C)")

C |= A
print("C 结果为：\(C)")
*/
```

The above program execution results:

```C 结果为：30
C 结果为：40
C 结果为：30
C 结果为：300
C 结果为：30
```

## Interval Operators

Swift offers two range operators.

Operators description Examples
Closed Interval Operators Closed interval operator (a ... b) a defined interval contains all values ​​from a to b (including a and b), b must be greater than or equal a. Closed interval iteration operator in a range of all values ​​is very useful, as in the for-in loop: 1 ... 5 range is 1, 2, 3, 4 and 5
Half-open interval operator Half-open interval (a .. 1 .. <5 interval value of 1, 2, 3, and 4

Following is a simple example of interval arithmetic:

```import Cocoa

print("闭区间运算符:")
for index in 1...5 {
print("\(index) * 5 = \(index * 5)")
}

print("半开区间运算符:")
for index in 1..<5 {
print("\(index) * 5 = \(index * 5)")
}
```

The above program execution results:

```闭区间运算符:
1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25

1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
```

## Other operators

Swift offers other types of operators, such as a mono-, di-, and the ternary operator.

• Unary operators on a single operating object manipulation (eg `-a` ). Unary operator operator minute pre and post operators, operators need to pre-operating immediately before the object (such as `!b` ), rear operator for an operation immediately after the object (such as `i++` ).
• Binary operators operate both operating objects (such as `2 + 3` ), it is in the home, as they appear between the two operands.
• Three ternary operator operating the operation target, and C languages, Swift is only a ternary operator, is ternary operator ( `a ? b : c` ).
Operators description Examples
Unary minus Add a digital front - Prefix -3 Or -4
Unary plus Digital Money Add + Prefix +6 Result 6
Ternary operator ? Condition X: Y If you add is true, the value of X, otherwise Y

The following is one dollar, a simple example of binary and ternary operations:

```import Cocoa

var A = 1
var B = 2
var C = true
var D = false
print("-A 的值为：\(-A)")
print("A + B 的值为：\(A + B)")
print("三元运算：\(C ? A : B )")
print("三元运算：\(D ? A : B )")
```

The above program execution results:

```-A 的值为：-1
A + B 的值为：3

```

## Operator Precedence

In an expression may contain a plurality of different operators connecting with different data types of data objects; since the expression has a variety of operations, a different order of operations may have different results even erroneous operation error, because when when an expression containing a variety of operations, according to a certain order must be combined in order to ensure the rationality and correctness of the results, the uniqueness of operation.

Priority in descending order from top to bottom, the top has the highest priority, the comma operator has the lowest priority.

The same priority level, according to the binding order of calculation. Most operations are calculated from left to right, only three priorities are right-to-left combination, they are unary operators, conditional operators, assignment operators.

The basic priorities need to remember:

• Optimal pointer, unary than binary operators. As the sign.
• First multiplication and division (modulus) after subtraction.
• First arithmetic shift operation after the last bit computing. Please pay particular attention to: << 1 2 & 3 + 7 is equivalent to (1 << (3 + 2)) & 7
• Final calculation logic operation
Operator Type Operators Binding direction
Expression evaluation () []. Expr ++ expr-- Left to Right
Unary operator

* & + -! ~ ++ Expr --expr

* /%

+ -

>> <<

<> <=> =

==! =

Right to Left
Bitwise Operators

&

^

|

&&

||

Left to Right
Ternary operator ?: Right to Left
Assignment Operators = + = - = * = / =% = >> = << = & = ^ = | = Right to Left
comma , Left to Right

The following is a simple example of operator precedence:

```import Cocoa

var A = 0

A = 2 + 3 * 4 % 5
print("A 的值为：\(A)")
```

The above program execution results:

```A 的值为：4
```

Analysis examples:

According to operator precedence, you can program the operation of the above steps resolves the following expression is equivalent to:

```2 + ((3 * 4) % 5)
```

The first step in the calculation: (3 * 4) = 12, so the expression is equivalent to:

`2 + (12 % 5)`

The second step to calculate 12% 5 = 2, so the expression is equivalent to:

`2 + 2`

At this point can be readily seen that the calculated results of four.