# Swift5.3 — 2.Basic Operators

An operator is a special symbol or phrase that you use to check, change, or combine values. For example, the addition operator (+) adds two numbers, and the logical AND operator (&&) combines two Boolean values.

`let i = 1 + 2if student && male`

# Content

1. Terminology
2. Assignment Operator
3. Arithmetic Operators
4. Range Operators
5. Logical Operators

# 1. Terminology

• 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). Binary operators are infix because they appear in between their two targets.

• ternary operators

Operate on three targets. Swift has only one ternary operator, the ternary conditional operator ( a ? b : c)

# 2. Assignment Operator

The assignment operator (left = right) initializes or updates the value of left with the value of right.

`let right= 10var left = 5left = right// left is now equal to 10`

If the right side of the assignment is tuple with multiple values, its elements can be decomposed into multiple constants or variables at once

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

operator ( = ) is not same as operator ( == ). So the following statement is not valid

`if x = y{    // This is not valid, because x = y does not return a value}`

# 3. Arithmetic Operators

Swift supports the four standard arithmetic operators +, — , *, /

`1 + 2        // equals 35 - 3        // equals 22 * 3        // equals 610.0 / 2.5   // equals 4.0`

Addition operator is also supported for String concatenation

`"hello, " + "world"    // equals "hello, world"`

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

`9 % 4    // equals 1  ( 9 = 4 * 2 + 1 , remainder is 1)10 % 3   // equals 1  ( 10 = 3 * 3 + 1, remainder is 1)8 % 3    // equals 2  ( 8 = 3 * 2 + 2, remainder is 2)-9 % 4   // equals -1 ( -9 = 4 * -2 + (-1), remainder is -1)`

The sign of a numeric value can be toggled using a prefixed -

`let three = 3let minusThree = -threelet plusThree = -minusThreelet minusSix = -6let alsoMinusSix = +minusSix   // alsoMinusSix equals -6// Unary plus operator doesn't actually do anything. But you still can use it to provide symmetry in your code for positive numbers.`

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 )
`1 == 1 // true because 1 is equal to 12 != 1   // true because 2 is not equal to 12 > 1    // true because 2 is greater than 11 < 2    // true because 1 is less than 21 >= 1   // true because 1 is greater than or equal to 12 <= 1   // false because 2 is not less than or equal to 1`

Comparison operators are often used in conditional statements, such as the if statement

`let name = "world"if name == "world" {    print("hello, world")}`

You can compare two tuples if they have the same type and the same number of values. Tuples are compared from left to right, one value at a time, until the comparison finds two values that aren’t equal. Bool type can not be compared

`(1, "zebra") < (2, "apple")// true, 1 is less than 2; "zebra" and "apple" are not compared(3, "apple") < (3, "bird")// true, 3 is equal to 3, and "apple" is less than "bird"(4, "dog") == (4, "dog")// true, 4 is equal to 4, and "dog" is equal to "dog"("blue", false) < ("purple", true)// Error, Boolean values can't be compared`

The ternary conditional operator is a special operator with three parts, which takes the form “ condition ? codeForTrue : codeForFalse ”. If condition is true it evaluates codeForTrue and return its value; otherwise, it evaluates codeForFalse and return its value

`if question{    answer1} else{    answer2}// This can be written in Ternary conditional operatorquestion? answer1 : answer2// Exampleslet height = 40let header = truelet width = height + (header ? 50: 20)// width is equal to 90`

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. If the value of a is non-nil, the value of b is not evaluated.

`var c = a??bvar c = a != nil ? a! : b`

The example below uses the nil-coalescing operator to choose between a default color name and an optional user-defined color name

`let defaultColorName = "red"var userDefinedColorName: String?    // defaults to nilvar colorNameToUse = userDefinedColorName ?? defaultColorName// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"`

# 4. Range Operators

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

The closed range operator ( a…b ) defines a range that runs from a to b, and includes the values a and b.

`for index in 1...3{    print("\(index) times 5 is \(index*5)")}// 1 times 5 is 5// 2 times 5 is 10// 3 times 5 is 15`

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

`let names = ["Anna", "Alex", "Brian", "Jack"]for i in 0..<names.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`

The closed range operator has an alternative form for ranges that continue as far as possible in one direction.

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

# 5. Logical Operators

The logical NOT operator ( !a ) inverts a Boolean value so that true becomes false, and false becomes true.

`let allowedEntry = falseif !allowedEntry {    print("ACCESS DENIED")}// !allowedEntry evaluates as true// 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.

`let enteredDoorCode = truelet passedRetinaScan = falseif enteredDoorCode && passedRetinaScan{    print("Welcome!")} else{    print("ACCESS DENIED")}// Prints "ACCESS DENIED"`

The logical OR operator ( a || b ) creates logical expressions where one of the two values has to be true for the overall expression to also be true.

`let enteredDoorCode = truelet passedRetinaScan = falseif enteredDoorCode ||passedRetinaScan{    print("Welcome!")} else{    print("ACCESS DENIED")}// Prints "Welcome!"`