Swift Operators

An operator is a symbol that tells the compiler to perform a mathematical or logical operation.

Swift provides the following operators:

  • Arithmetic operators
  • Comparison operators
  • Logical operators
  • Bitwise operators
  • Assignment operators
  • Range operators
  • Other operators

In this chapter, we will introduce arithmetic operators, relational operators, logical operators, bitwise operators, assignment operators, and other operators in detail.


Arithmetic Operators

The following table lists the arithmetic operators supported by the Swift language, where variable A is 10 and variable B is 20:

Operator Description Example
+ Plus A + B result is 30
− Minus A − B result is -10
* Multiplication A * B result is 200
/ Division B / A result is 2
% Remainder B % A result is 0

Note:In Swift 3, it has been removed.++、--。

Example

The 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 += 1   // 类似 A++
print("A += 1 后 A 的值为 \(A)")
B -= 1   // 类似 B--
print("B -= 1 后 B 的值为 \(B)")

The output of the above program is:

A + B 结果为:30
A - B 结果为:-10
A * B 结果为:200
B / A 结果为:2
A += 1 后 A 的值为 11
B -= 1 后 B 的值为 19

Comparison Operators

The following table lists the comparison operators supported by the Swift language, where variable A is 10 and variable B is 20:

Operator Description Example
== Equal to (A == B) is false.
!= Not equal to (A != B) is true.
> Greater than (A > B) is false.
< Less than (A < B) is true.
>= Greater than or equal to (A >= B) is false.
<= Less than or equal to (A <= B) is true.

Example

The 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 output of the above program is:

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 logical operators supported by the Swift language, where variable A is true and variable B is false:

Operator Description Example
&& Logical AND. If both sides of the operator are TRUE, then it is TRUE. (A && B) is false.
|| Logical OR. If at least one side of the operator is TRUE, then it is TRUE. (A || B) is true.
! Logical NOT. Inverts the Boolean value, turning true into false and false into true. !(A && B) is true.

The following is a simple example of logical operations:

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 output of the above program is:

A && B 结果为:false
A || B 结果为:true
!A 结果为:false
!B 结果为:true

Bitwise Operators

Bitwise operators are used to perform operations on binary bits. ~, &, |, and ^ are respectively NOT, AND, OR, and XOR operations, as shown in 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; the binary representations of the two variables are:

A = 0011 1100

B = 0000 1101

Perform bitwise operations:

Operator Description Diagram Example
& Bitwise AND. The bitwise AND operator operates on two numbers and returns a new number, where each bit is 1 only if the corresponding bits of both input numbers are 1. (A & B) result is 12, binary is 0000 1100
| Bitwise OR. The bitwise OR operator | compares two numbers and returns a new number, where each bit is set to 1 if the corresponding bits of the two input numbers are not both 0 (i.e., either one is 1, or both are 1). (A | B) result is 61, binary is 0011 1101
^ Bitwise XOR. The bitwise XOR operator ^ compares two numbers and returns a number, where each bit is set to 1 if the corresponding bits of the two input numbers are different, and set to 0 if they are the same. (A ^ B) result is 49, binary is 0011 0001
~ The bitwise NOT operator ~ inverts every bit of an operand. (~A ) result is -61, binary is 1100 0011 in 2's complement form.
<< Bitwise left shift. The left shift operator (<<) shifts all bits of the operand to the left by the specified number of places.

The following diagram shows the result of 11111111 << 1 (11111111 shifted left by one bit). The blue digits indicate the shifted bits, the gray digits indicate the discarded bits, and the empty positions are filled with orange 0s.

A << 2 result is 240, binary is 1111 0000
>> Bitwise right shift. The right shift operator (>>) shifts all bits of the operand to the right by the specified number of places.

The following diagram shows the result of 11111111 >> 1 (11111111 shifted right by one bit). The blue digits indicate the shifted bits, the gray digits indicate the discarded bits, and the empty positions are filled with orange 0s.

A >> 2 result is 15, binary is 0000 1111

The following is a simple example of bitwise 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 output of the above program is:

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

Assignment Operators

The following table lists the basic assignment operations in the Swift language:

Operator Description Example
= Simple assignment operation, assigns the right operand to the left operand. C = A + B assigns the result of A + B to C
+= Add and assign, adds the left and right operands and assigns the result to the left operand. C += A is equivalent to C = C + A
-= Subtract and assign, subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A
*= Multiply and assign, multiplies the left and right operands and assigns the result to the left operand. C *= A is equivalent to C = C * A
/= Divide and assign, divides the left operand by the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A
%= Modulo and assign, takes the remainder of the left and right operands and assigns the result to the left operand. C %= A is equivalent to C = C % A
<<= Bitwise left shift and assign C <<= 2 is equivalent to C = C << 2
>>= Bitwise right shift and assign C >>= 2 is equivalent to C = C >> 2
&= Bitwise AND and assign C &= 2 is equivalent to C = C & 2
^= Bitwise XOR and assign C ^= 2 is equivalent to C = C ^ 2
|= Bitwise OR and assign C |= 2 is equivalent to C = C | 2

The following is a simple example of assignment operations:

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 output of the above program is:

C 结果为:30
C 结果为:40
C 结果为:30
C 结果为:300
C 结果为:30

Range Operators

Swift provides two range operators.

Operator Description Example
Closed range operator The closed range operator (a...b) defines a range that includes all values from a to b (including a and b), and b must be greater than or equal to a. The closed range operator is very useful when iterating over all values in a range, such as in a for-in loop: The range 1...5 has values 1, 2, 3, 4, and 5
Half-open range operator The half-open range operator (a..<b) defines a range from a to b but does not include b. It is called half-open because it includes the first value but not the last value. The range 1..<5 has values 1, 2, 3, and 4

The following is a simple example of range operations:

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 output of the above program is:

闭区间运算符:
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 provides other types of operators, such as unary, binary, and ternary operators.

  • A unary operator operates on a single operand (such as-a). Unary operators are divided into prefix and postfix operators. A prefix operator must immediately precede its operand (e.g.!b), postfix operators must immediately follow the operand (e.g., c!).Notes:In Java/C, there is no syntax like c!. In Swift, it is used to get a value from an Optional type.
  • Binary operators operate on two operands (e.g.2 + 3), and are infix because they appear between the two operands.
  • Ternary operators operate on three operands. Like C, Swift has only one ternary operator, which is the ternary conditional operator (a ? b : c)。
Operator Description Example
Unary minus Add a - sign prefix before the number -3 or -4
Unary plus Add a + sign prefix before the number +6 results in 6
Ternary operator condition ? X : Y Ifconditionis true, the value is X, otherwise Y

The following are simple examples of unary, 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 output of the above program is:

-A 的值为:-1
A + B 的值为:3
三元运算:1
三元运算:2

Operator Precedence

An expression may contain multiple data objects of different data types connected by different operators. Since an expression can have multiple operations, different orders of evaluation may produce different results or even operation errors. Therefore, when an expression contains multiple operations, it must be combined in a certain order to ensure the rationality of the operation and the correctness and uniqueness of the result.

Precedence decreases from top to bottom; the top has the highest precedence, and the comma operator has the lowest precedence.

At the same precedence, operations are performed according to associativity. Most operations are evaluated from left to right, and only three precedence levels are right-to-left associative: unary operators, conditional operators, and assignment operators.

Basic precedence rules to remember:

  • Pointers have the highest precedence, and unary operations take precedence over binary operations. For example, plus and minus signs.
  • Multiplication, division (modulo) before addition and subtraction.
  • Arithmetic operations first, then shift operations, and finally bitwise operations. Please note: 1 << 3 + 2 & 7 is equivalent to (1 << (3 + 2))&7
  • Logical operations are evaluated last.

Swift operator precedence (from high to low):

Operator Example
Bitwise operators >> &<< &>> >>
Multiplication operators &* % & * /
Addition operators | &+ &- + -  ^
Range operators ..< ...
Type casting operators is as
Nil coalescing operator ??
Comparison operators != > < >= <= === ==
Logical AND operator &&
Logical OR operator ||
Wave arrow ~>
Ternary operator ?:
Arrow function ( )
Assignment operator |= %= /= &<<= &>>= &= *= >>= <<= ^= += -=

The following is a simple example of operator precedence:

import Cocoa

var A = 0

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

The output of the above program is:

A 的值为:4

Example analysis:

According to operator precedence, the operations in the above program can be analyzed into the following steps. The expression is equivalent to:

2 + ((3 * 4) % 5)

Step 1: (3 * 4) = 12, so the expression is equivalent to:

2 + (12 % 5)

Step 2: 12 % 5 = 2, so the expression is equivalent to:

2 + 2

At this point, it is easy to see that the result of the calculation is 4.

Other extensions