忍者刘米米

3. Basic Operators

Assignment Operator

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

1
2
3
4
5
6
7
let b = 10
var a = 5
a = b
// a is now equal to 10

let (x, y) = (1, 2)
// x is equal to 1, and y is equal to 2

Unlike the assignment operator in C and Objective-C, the assignment operator in Swift does not itself return a value.

1
2
3
if x = y {
// This is not valid, because x = y does not return a value. should use "=="
}

Arithmetic Operators

Unlike the arithmetic operators in C and Objective-C, the Swift arithmetic operators do not allow values to overflow by default.

1
2
3
4
5
6
7
8
1 + 2       // equals 3
5 - 3 // equals 2
2 * 3 // equals 6
10.0 / 2.5 // equals 4.0

9 % 4 // equals 1
-9 % 4 // equals -1
// a % b and a % -b always give the same answer.

Compound Assignment Operators

1
2
3
4
5
var a = 1
a += 2

// a is now equal to 3
// a += 2 is shorthand for a = a + 2.

Comparison Operators

  • Each of the comparison operators returns a Bool value to indicate whether or not the statement is true
  • Swift also provides two identity operators (=== and !==), which you use to test whether two object references both refer to the same object instance
1
2
3
4
5
6
1 == 1   // true because 1 is equal to 1
2 != 1 // true because 2 is not equal to 1
2 > 1 // true because 2 is greater than 1
1 < 2 // true because 1 is less than 2
1 >= 1 // true because 1 is greater than or equal to 1
2 <= 1 // false because 2 is not less than or equal to 1

Tuple comparison

  • The Swift standard library includes tuple comparison operators for tuples with fewer than seven elements. To compare tuples with seven or more elements, you must implement the comparison operators yourself.
  • Tuples are compared from left to right, one value at a time, until the comparison finds two values that aren’t equal.
1
2
3
4
5
6
7
8
(1, "zebra") < (2, "apple")   
// true because 1 is less than 2; "zebra" and "apple" are not 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 shorthand for the code below:

1
2
3
4
5
if question {
answer1
} else {
answer2
}

question ? answer1 : answer2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
// rowHeight is equal to 90

//The preceding example is shorthand for the code below:
let contentHeight = 40
let hasHeader = true
let rowHeight: Int
if hasHeader {
rowHeight = contentHeight + 50
} else {
rowHeight = contentHeight + 20
}
// rowHeight is equal to 90

Nil-Coalescing Operator

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

1
a != nil ? a! : b

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

1
2
3
4
5
6
7
8
9
let defaultColorName = "red"
var userDefinedColorName: String? // defaults to nil

var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"

userDefinedColorName = "green"
colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is not nil, so colorNameToUse is set to "green"

Range Operators

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.

1
2
3
4
5
6
7
8
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25

Half-Open Range Operator

The half-open range operator (a..<b) defines a range that runs from a to b, but does not include b.

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

Logical Operators

The logical NOT operator (!a)

1
2
3
4
5
let allowedEntry = false
if !allowedEntry {
print("ACCESS DENIED")
}
// Prints "ACCESS DENIED"

The logical AND operator (a && b) creates logical expressions where both values must be true for the overall expression to also be true.

1
2
3
4
5
6
7
8
let enteredDoorCode = true
let passedRetinaScan = false
if enteredDoorCode && passedRetinaScan {
print("Welcome!")
} else {
print("ACCESS DENIED")
}
// Prints "ACCESS DENIED"

The logical OR operator (a || b)

1
2
3
4
5
6
7
8
let hasDoorKey = false
let knowsOverridePassword = true
if hasDoorKey || knowsOverridePassword {
print("Welcome!")
} else {
print("ACCESS DENIED")
}
// Prints "Welcome!"

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

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