Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Operators

Swift Operators

An operator is a symbol that tells the compiler to perform a certain operation on operands, such as addition, comparison, or logical judgment.

Swift's operators can be broadly divided into arithmetic, overflow, comparison, logical, bitwise, range, and nil-coalescing categories.


Operator categories

The table below groups Swift's common operators by purpose; later sections will expand on each category.

Category operator
Arithmetic + - * / %
Overflow &+ &- &*
Comparison == != < <= > >= === !==
Logic && \|\| !
Bitwise operations & \| ^ ~ << >> &<< &>>
Range a...b a.. ...b a...
Null coalescing ??
Ternary 条件 ? 值1 : 值2

Arithmetic operators

Arithmetic operators are used for addition, subtraction, multiplication, division, and remainder; in the table below, A is 10 and B is 20.

operator Description Example
+ Addition A + B evaluates to 30
- Subtraction A - B evaluates to -10
* Multiplication A * B evaluates to 200
/ Division B / A evaluates to 2
% Remainder B % A evaluates to 0

Example

let A

=

10

let B

=

20

print

(

"A + B evaluates to: (A + B)"

)

print

(

"A - B evaluates to: (A - B)"

)

print

(

"A * B evaluates to: (A * B)"

)

print

(

"B / A evaluates to: (B / A)"

)

print

(

"B % A evaluates to: (B % A)"

)

The execution result of the above program is:



A + B 结果为:30

A - B 结果为:-10

A * B 结果为:200

B / A 结果为:2

B % A 结果为:0

Integer division truncates the decimal part

When two integers are divided, the result is still an integer, with the fractional part discarded directly (truncated toward zero), and the sign of the remainder matches that of the dividend.

Example

print

(

"7 / 2 = (7 / 2)"

)

print

(

"(-7) / 2 = ((-7) / 2)"

)

print

(

"7 % 3 = (7 % 3)"

)

print

(

"(-7) % 3 = ((-7) % 3)"

)

// To get a decimal result, write at least one side as a floating-point number

print

(

"7.0 / 2 = (7.0 / 2)"

)

The execution result of the above program is:



7 / 2 = 3

(-7) / 2 = -3

7 % 3 = 1

(-7) % 3 = -1

7.0 / 2 = 3.5

If the result of an operation exceeds the range that a type can represent, Swift will terminate the program directly (triggering a trap), rather than quietly giving an incorrect result.

Example

// The range of Int8 is -128...127; the following line triggers an overflow trap at runtime

let small

:

Int8

=

127

let overflow

=

small

1

print

(

overflow

)

The program will stop immediately when execution reaches this line, producing no output and not assigning an incorrect value to overflow.


Overflow operators

Swift provides three overflow operators &+, &-, and &*; they do not trigger a trap, but instead let the result wrap around according to the bit width.

The result of wrapping is deterministic: exceeding the upper bound restarts from the lower bound, and vice versa.

Example

let maxInt

=

Int.

max

print

(

"Int.max = (maxInt)"

)

print

(

"Int.max &+ 1 = (maxInt &+ 1)"

)

let minInt

=

Int.

min

print

(

"Int.min &- 1 = (minInt &- 1)"

)

let x8

:

Int8

=

100

print

(

"Int8's 100 &* 2 = (x8 &* 2)"

)

The execution result of the above program is:



Int.max = 9223372036854775807

Int.max &+ 1 = -9223372036854775808

Int.min &- 1 = 9223372036854775807

Int8 的 100 &* 2 = -56

Note:Overflow operators are designed for scenarios that need explicit wrapping semantics, such as hashing, encryption, and game random numbers. Ordinary business calculations should still use +、-、*, so that overflow is exposed as early as possible.


Comparison operators

Comparison operators return a Bool; in the table below, A is 10 and B is 20.

operator Description Example
== Equal (A == B) is false
!= Not equal (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
=== Reference equality (two variables pointing to the same object) Only for class instances
!== Reference inequality Only for class instances

Example

let A

=

10

let B

=

20

print

(

"A == B evaluates to: (A == B)"

)

print

(

"A != B evaluates to: (A != B)"

)

print

(

"A > B evaluates to: (A > B)"

)

print

(

"A < B result is: (A < B)"

)

print

(

"A >= B evaluates to: (A >= B)"

)

print

(

"A <= B evaluates to: (A <= B)"

)

The execution result of the above program is:



A == B 结果为:false

A != B 结果为:true

A > B 结果为:false

A < B result is: true

A >= B 结果为:false

A <= B 结果为:true


Logical operators

Logical operators operate on Bool values; in the table below, A is true and B is false.

operator Description Example
&& Logical AND, true only when both sides are true (A && B) is false
\|\| Logical OR, true as long as at least one side is true (A || B) is true
! Logical NOT, turns true into false and false into true !A is false

Example

let A

=

true

let B

=

false

print

(

"A && B evaluates to: (A && B)"

)

print

(

"A || B evaluates to: (A || B)"

)

print

(

"!A evaluates to: (!A)"

)

print

(

"!B evaluates to: (!B)"

)

The execution result of the above program is:



A && B 结果为:false

A || B 结果为:true

!A 结果为:false

!B 结果为:true

&& and || are short-circuit evaluated: when the left side already determines the result, the right side is not evaluated.


Bitwise operators

Bitwise operators operate directly on the binary bits of integers; the commonly used ones are NOT, AND, OR, XOR, and shift.

operator Description Example (A = 60, B = 13)
& Bitwise AND, the bit is 1 only if both bits are 1 A & B evaluates to 12
\| Bitwise OR, the bit is 1 if either bit is 1 A | B evaluates to 61
^ Bitwise XOR, the bit is 1 only if the two bits differ A ^ B evaluates to 49
~ Bitwise NOT, every bit is inverted ~A evaluates to -61
<< Shift left, fill low bits with 0 A << 2 evaluates to 240
>> Right shift; for signed numbers the high-order bits are filled with the sign bit A >> 2 evaluates to 15
&<< Overflowing left shift: bits shifted out are simply discarded, with no checks See the example below
&>> Overflowing right shift: bits shifted out are simply discarded, with no checks See the example below

Example

let p

=

60

 

// Binary 0011 1100

let q

=

13

 

// Binary 0000 1101

print

(

"p & q evaluates to: (p & q)"

)

print

(

"p | q evaluates to: (p | q)"

)

print

(

"p ^ q evaluates to: (p ^ q)"

)

print

(

"~p evaluates to: (~p)"

)

print

(

"p << 2 evaluates to: (p << 2)"

)

print

(

"p >> 2 evaluates to: (p >> 2)"

)

The execution result of the above program is:



p & q 结果为:12

p | q 结果为:61

p ^ q 结果为:49

~p 结果为:-61

p << 2 结果为:240

p >> 2 结果为:15

For normal shifts, if the shifted-out bits contain valid data, an overflow trap is still triggered; &<< and &>> simply discard the shifted-out bits.

Example

let small

:

Int8

=

127

print

(

"Int8's 127 &<< 1 = (small &<< 1)"

)

print

(

"Int8's -128 &>> 1 = ((Int8.min) &>> 1)"

)

The execution result of the above program is:



Int8 的 127 &<< 1 = -2

Int8 的 -128 &>> 1 = -64


Range operators

Range operators are used to represent a continuous range of values, and there are four common forms.

Syntax Name Meaning Example
a...b closed range Contains a and b 1...5 are 1, 2, 3, 4, 5
a.. Half-open range Contains a, but not b 1..<5 are 1, 2, 3, 4
...b One-sided range (prefix) From the minimum value to b array[...1] Take the first two elements
a... One-sided range (postfix) From a to the maximum value array[2...] Take all elements starting from the third

Example

for

i in

1

...

3

{

    print

(

"closed range 1...3 -> (i)"

)

}

for

i in

1

..

<

3

{

print

(

"half-open range 1..<3 -> (i)"

)

}

let names

=

[

"Runoob"

,

"RUNOOB"

,

"Runoob Tutorial"

,

"Swift"

]

print

(

Array

(

names

[

...

1

]

)

)

 

// The first two

print

(

Array

(

names

[

2

...

]

)

)

 

// All elements starting from the 3rd

// Check whether a value falls within a range

print

(

(

1

...

5

)

.

contains

(

3

)

)

print

(

(

1

...

5

)

.

contains

(

6

)

)

The execution result of the above program is:



闭区间 1...3 -> 1

闭区间 1...3 -> 2

闭区间 1...3 -> 3

半开区间 1..<3 -> 1

半开区间 1..<3 -> 2

["Runoob", "RUNOOB"]

["Runoob Tutorial", "Swift"]

true

false


Null coalescing operator ??

The null coalescing operator ?? is used to provide a default value for an optional: if the left side has a value, take the left side; if it is nil, take the right side.

It is equivalent to a != nil ? a! : b, but is written more concisely and evaluates the left-hand expression only once.

Example

let siteName

:

String

?

=

nil

let siteName2

:

String

?

=

"www.runoob.com"

// If the left side is nil, use the default value

print

(

siteName

??

"RUNOOB"

)

// If the left side has a value, use the left-side value directly

print

(

siteName2

??

"RUNOOB"

)

// Values retrieved from a dictionary are also optional and can use ?? as well

let info

:

[

String

:

String

]

=

[

"name"

:

"Runoob"

]

print

(

info

[

"name"

]

??

"File %s type is: %s%n"

)

print

(

info

[

"site"

]

??

"File %s type is: %s%n"

)

The execution result of the above program is:



RUNOOB

www.runoob.com

Runoob

未知

Note:?? The type on the right must match the left side's unwrapped type, or be automatically convertible. For more on optional types, see Chapter 29 "Swift optional types》。


Ternary Operator

The ternary operator condition ? value1 : value2 is the expression form of if-else; if the condition is true, "value1" is taken, otherwise "value2" is taken.

Example

let score

=

85

print

(

score

=

60

?

"Pass"

:

"Fail"

)

let A

=

1

let B

=

2

let C

=

true

print

(

C

?

A

:

B

)

The execution result of the above program is:



及格

1


Operator precedence and associativity

When multiple operators appear in a single expression, which one is evaluated first is decided by precedence; for operators of the same precedence, associativity decides whether evaluation starts from the left or the right.

The table below shows the precedence groups actually defined in the Swift standard library, arranged from highest to lowest.

Priority groups (from high to low) operator Associativity
BitwiseShiftPrecedence << >> &<< &>> None
MultiplicationPrecedence * / % &* & Left-associative
AdditionPrecedence + - &+ &- \| ^ Left-associative
RangeFormationPrecedence ..< ... None
CastingPrecedence is as None
NilCoalescingPrecedence ?? Right-associative
ComparisonPrecedence == != < <= > >= === !== None
LogicalConjunctionPrecedence && Left-associative
LogicalDisjunctionPrecedence \|\| Left-associative
TernaryPrecedence ? : Right-associative
AssignmentPrecedence = += -= *= /= etc. Right-associative

Note:Swift turns & placed at multiplication precedence, and put | and ^ placed at addition precedence, which is different from the C language. In C a & b == c is calculated first ==, while in Swift it is computed first &. When writing an expression, add parentheses wherever they are needed, and don't rely on memory.

Example

// First compute 3 * 4, then % 5, and finally add 2

let result

=

2

3

4

%

5

print

(

"2 + 3 * 4 % 5 = (result)"

)

// Parentheses can change the order

print

(

"(2 + 3) * 4 % 5 = ((2 + 3) * 4 % 5)"

)

The execution result of the above program is:



2 + 3 * 4 % 5 = 4

(2 + 3) * 4 % 5 = 0


Common questions

The following issues are the easiest to run into when using Swift operators.

Problem Description
Why 7 / 2 get 3 instead of 3.5 When two integers are divided, the result is an integer and the fraction is truncated; for a fractional result, use 7.0 / 2
Why does overflow cause a crash instead of reporting an error Swift checks for overflow by default and triggers a trap, which is by design for safety; when wrapping is genuinely needed, use &+ Series
== and === what is the difference == Compares whether values are equal,=== Compares whether two references point to the same object
?? Can the left side be used if it is not an optional value? No, it requires the left side to be an optional type.
Can a range operator be used directly as an array index? Yes, what you get from slicing is ArraySlice, use it when needed Array() Convert back to an array