# 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 + 2`

if student && male

# Content

- Terminology
- Assignment Operator
- Arithmetic Operators
- Range Operators
- 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

**operators appear immediately after their target ( such as c!)**

*postfix*- 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= 10`

var left = 5

left = 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 3`

5 - 3 // equals 2

2 * 3 // equals 6

10.0 / 2.5 // equals 4.0

Addition operator is also supported for ** String **concatenation

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

## Remainder Operator

The remainder operator ( ** a % b** ) works out how many multiples of

**will fit inside**

*b***and returns the value that is left over (known as the remainder)**

*a*`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)

## Unary Plus, Minus Operator

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

let three = 3

let minusThree = -three

let plusThree = -minusThreelet minusSix = -6

let 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.

## Compound Assignment 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 )

`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

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

## Ternary Conditional Operator

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 operator

question? answer1 : answer2// Examples

let height = 40

let header = true

let width = height + (header ? 50: 20)

// width is equal to 90

## Nil-Coalescing Operator

The nil-coalescing operator ( ** a ?? b** ) unwraps an optional

**if it contains a value, or returns a default value**

*a***if**

*b***is nil. If the value of**

*a***is non-nil, the value of**

*a***is not evaluated.**

*b*`var c = a??b`

var 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.

## Closed Range Operator

The closed range operator ( ** a…b** ) defines a range that runs from

**to**

*a***, and includes the values**

*b***and**

*a***.**

*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

## Half-Open Range Operator

The half-open range operator ( ** a..<b** ) defines a range that runs from

**to**

*a***, but doesn’t include**

*b***.**

*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

## One-Sided Ranges

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

## Logical NOT Operator

The logical ** NOT** operator (

**) inverts a Boolean value so that**

*!a***becomes**

*true***, and**

*false***becomes**

*false***.**

*true*`let allowedEntry = false`

if !allowedEntry {

print("ACCESS DENIED")

}

// !allowedEntry evaluates as true

// Prints "ACCESS DENIED"

## Logical AND Operator

The logical ** AND** operator (

**) creates logical expressions where both values must be true for the overall expression to also be true.**

*a && b*`let enteredDoorCode = true`

let passedRetinaScan = false

if enteredDoorCode && passedRetinaScan{

print("Welcome!")

} else{

print("ACCESS DENIED")

}

// Prints "ACCESS DENIED"

## Logical OR Operator

The logical ** OR** operator (

**) creates logical expressions where one of the two values has to be true for the overall expression to also be true.**

*a || b*`let enteredDoorCode = true`

let passedRetinaScan = false

if enteredDoorCode ||passedRetinaScan{

print("Welcome!")

} else{

print("ACCESS DENIED")

}

// Prints "Welcome!"