Swift_Note Operators

🧩 Terminology

Operators are unary, binary, or ternary: (一元、二元、三元)

  • Unary operators operate on a single target (such as -a). Unary prefix operators appear immediately before their target (such as !b), and unary postfix operators appear immediately after their target (such as c!).
  • Binary operators operate on two targets (such as 2 + 3) and are infix because they appear in between their two targets.
  • Ternary operators operate on three targets. Like C, Swift has only one ternary operator, the ternary conditional operator (a ? b : c).

The values that operators affect are operands. In the expression 1 + 2, the + symbol is an infix operator and its two operands are the values 1 and 2.

Assignment Operator (赋值运算符)

The assignment operator (a = b) initializes or updates the value of a with the value of b:

1
2
3
let b = 10
var a = 5
a = b

Arithmetic Operators (+,-,*,/)

Basic Operators

An operator is a special symbol or phrase that you use to check, change, or combine values.

Swift supports the four standard arithmetic operators for all number types:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)

Remainder Operator (求余)

The remainder operator (a % b) works out how many multiples of b will fit inside a and returns the value that’s left over (known as the remainder).

Note

The remainder operator (%) is also known as a modulo operator in other languages. However, its behavior in Swift for negative numbers means that, strictly speaking, it’s a remainder rather than a modulo operation.

Unary Minus Operator

1
2
3
let three = 3
let minusThree = -three       // minusThree equals -3
let plusThree = -minusThree   // plusThree equals 3, or "minus minus three"

Unary Plus Operator

The unary plus operator (+) simply returns the value it operates on, without any change:

1
2
let minusSix = -6
let alsoMinusSix = +minusSix  // alsoMinusSix equals -6

Compound Assignment Operators

Like C, Swift provides compound assignment operators that combine assignment (=) with another operation. One example is the addition assignment operator (+=):

🧩 Comparison Operators (比较运算符)

Swift supports the following comparison operators:

  • Equal to (a == b)
  • Not equal to (a != b)
  • Greater than (a > b)
  • Less than (a < b)
  • Greater than or equal to (a >= b)
  • Less than or equal to (a <= b)

Note

Swift also provides two identity operators (=== and !==), which you use to test whether two object references both refer to the same object instance.

short-circuit comparison(短路比较)

1
2
3
(1, "zebra") < (2, "apple")   // true because 1 is less than 2; "zebra" and "apple" aren't compared
(3, "apple") < (3, "bird")    // true because 3 is equal to 3, and "apple" is less than "bird"
(4, "dog") == (4, "dog")      // true because 4 is equal to 4, and "dog" is equal to "dog"

Ternary Conditional Operator

The ternary conditional operator is a special operator with three parts, which takes the form question ? answer1 : answer2.

1
let rowHeight = contentHeight + (hasHeader ? 50 : 20)

Nil-Coalescing Operator

The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil.

The nil-coalescing operator is shorthand for the code below:

1
a != nil ? a! : b

Note

If the value of a is non-nil, the value of b isn’t evaluated. This is known as short-circuit evaluation.

Range Operators

Swift includes several range operators, which are shortcuts for expressing a range of values.

Closed Range Operator

The closed range operator (a…b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.

Half-Open Range Operator

The half-open range operator (a..<b) defines a range that runs from a to b, but doesn’t include b. It’s said to be half-open because it contains its first value, but not its final value. As with the closed range operator, the value of a must not be greater than b. If the value of a is equal to b, then the resulting range will be empty.

Half-open ranges are particularly useful when you work with zero-based lists such as arrays, where it’s useful to count up to (but not including) the length of the list:

1
2
3
4
5
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
    print("Person \(i + 1) is called \(names[i])")
}

One-Sided Ranges

The closed range operator has an alternative form for ranges that continue as far as possible in one direction — for example, a range that includes all the elements of an array from index 2 to the end of the array. In these cases, you can omit the value from one side of the range operator. This kind of range is called a one-sided range because the operator has a value on only one side. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
for name in names[2...] {
    print(name)
}
// Brian
// Jack

for name in names[...2] {
    print(name)
}
// Anna
// Alex
// Brian

The half-open range operator also has a one-sided form that’s written with only its final value. Just like when you include a value on both sides, the final value isn’t part of the range. For example:

1
2
3
4
5
for name in names[..<2] {
    print(name)
}
// Anna
// Alex

One-sided ranges can be used in other contexts, not just in subscripts. You can’t iterate over a one-sided range that omits a first value, because it isn’t clear where iteration should begin. You can iterate over a one-sided range that omits its final value; however, because the range continues indefinitely, make sure you add an explicit end condition for the loop. You can also check whether a one-sided range contains a particular value, as shown in the code below.

1
2
3
4
let range = ...5
range.contains(7)   // false
range.contains(4)   // true
range.contains(-1)  // true

Logical Operators

Logical operators modify or combine the Boolean logic values true and false. Swift supports the three standard logical operators found in C-based languages:

  • Logical NOT (!a)
  • Logical AND (a && b)
  • Logical OR (a || b)

Note

The Swift logical operators && and || are left-associative, meaning that compound expressions with multiple logical operators evaluate the leftmost subexpression first.

1
2
3
4
5
6
if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {
    print("Welcome!")
} else {
    print("ACCESS DENIED")
}
// Prints "Welcome!"

Explicit Parentheses ()

It’s sometimes useful to include parentheses when they’re not strictly needed, to make the intention of a complex expression easier to read. In the door access example above, it’s useful to add parentheses

1
2
3
4
5
6
if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {
    print("Welcome!")
} else {
    print("ACCESS DENIED")
}
// Prints "Welcome!"

The parentheses make it clear that the first two values are considered as part of a separate possible state in the overall logic. The output of the compound expression doesn’t change, but the overall intention is clearer to the reader. Readability is always preferred over brevity; use parentheses where they help to make your intentions clear.

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy