# Swift Programming – Basic Operators

In this tutorial you’ll learn about basic operators in Swift. To follow along, it is recommended to have a Mac and the Xcode IDE installed on it. This tutorial makes use of the Xcode playground for compilation of the Swift codes. If you do not have a Mac, you may try using the open-source code editors which support different operating systems such as Atom, SublimeText or VSCode.

Basic Operators

Operators are special symbols or phrases that are used to check, change or combine values. This tutorial explains some common operators of Swift such as the addition operator (+), the logical AND operator (&&), the assignment operator (=), equal to operator (==) and arithmetic operators (+,,*,/).

Terminology

There are three types of operators in Swift.

Unary operators are applied on a single target such as (-x). There are two types of such operators, Unary prefix operators appears before their target such as (-x) and Unary postfix operators appears after their target such as (y!).

Binary operators are applied in between two targets such as (x + y).

Ternary operators are applied on three targets. Swift has only one such operator which is the ternary conditional operator such as (x ? y : z).

The targets are known as operands for example in the case of (x + y), (+) is the binary operator and the values (x and y) are its two operands.

Assignment Operator

The assignment operator initializes or updates a value. An example can be:

```let x = 4
var y = 3
y = x // y has the value of 4
```

Let’s say you’re declaring a tuple constant on the right side assignment, you can decompose its elements like the following:

```let (k, h) = (2, 4) // k has a value of 2 and h has a value of 4
```

Arithmetic Operators

Swift supports the standard arithmetic operators for all number types, namely, addition (+), subtraction (), multiplication (*) and division (/).

```let i = 3, j = 6
let addition = i + j // 9
let subtraction = j - i // 3
let multiplication = i * j // 18
let division = Double(j)/Double(i) // 2.0
```

The addition operator also supports String concatenation:

```let hello = "Hello"
let world = "World"
let concatenation = hello + " " + world + "!"
```

Remainder Operator

The remainder operator (%) can be used to obtain the remainder value of a division:

```let seven = 7
let two = 2
let remainder = seven % two // 1
```

Compound Assignment Operators

Compound Assignment Operators are the combination of assignment operator (=) with some other operator. An example with the addition assignment operator:

```var x1 = 10 // x1 = 10
x1 += 9 // x1 = 19
```

The x1 += 9 is the short version of x1 = x1 + 9.

Comparison Operators

Comparison Operators return a bool value after evaluating a statement. These are:

• (x == y), x is equal to (==) y
• (x != y), x is not equal to (!=) y
• (x > y), x is greater than (>) y
• (x < y), x is less than (<) y
• (x >= y), x is greater than or equal to (>=) y
• (x <= y), x is less than or equal to (<=) y

Tuples with the same types and the same number of values can be compared from left to right, one value at a time until two unequal values are found. Examples can be:

```var value1 = (19, "ios")
var value2 = (20, "android")
var isComparisonTrue = value1 < value2
/* evaluates to true because 19 is compared to 20 and 19 is indeed less than 20, the second values are not compared */

value1 = (21, "application")
value2 = (21, "development")
isComparisonTrue = value1 < value2
/* evaluates to true because 21 is equal to 21 and "application" is indeed less than "development" */

value1 = (22, "mobile")
value2 = (22, "mobile")
isComparisonTrue = value1 == value2
/* evaluates to true because 22 is equal to 22 and "mobile" is equal to "mobile" */
```

Ternary Conditional Operator

The Ternary Conditional Operator :

```let isRaining = false
isRaining ? print("It’s raining") : print("It’s not raining")
```

is shorthand for:

```if isRaining {
print("It’s raining")
} else {
print("It’s not raining")
}
```

Nil-Coalescing Operator

The Nil-Coalescing Operator can be used when unwrapping an optional:

```let favoriteFruit = "Pineapple"
var fruit: String? // fruit is assigned to nil
var output = fruit ?? favoriteFruit
```

?? is the Nil-Coalescing Operator, meaning that if fruit is nil then take the default value of favoriteFruit. If you had to write that code using the Ternary Conditional Operator:

```output = (fruit == nil) ? favoriteFruit : fruit!
```

Let’s add a value to the variable fruit:

```fruit = "apple"
output = fruit ?? favoriteFruit
```

Range Operators

Range Operators are shortcuts for expressing a range of values. There are three types of Range Operators:

• Closed Range Operator (x…y)
• Half-Open Range Operator (x..<y)
• One-Sided Range Operator (…y) or (x…)
```/*
* Closed Range Operator (x...y)
*/

for i in 1...12 {
print("\(i) x 2 = \(i * 2)")
}

/*
* Half-Open Range Operator (x..<y)
*/

for j in 1..<13 {
print("\(j) x 3 = \(j * 3)")
}

/*
* One-Sided Range Operator (...y) or (x...)
*/

// an array of String type
let names = ["Michael", "Lincoln", "Sara", "Sucre"]

// range 0 - 1
for name in names[...1] {
print("name is \(name)")
}

// range 2 - 3
for name in names[2...] {
print("name is \(name)")
}
```

Logical Operators

Logical Operators are used for some modification or combination of the Boolean logic values true and false. These are:

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

Logical NOT Operator

The Logical NOT Operator inverts a bool value from true to false or false to true:

```var isSunny = false // isSunny has the value false
isSunny = !isSunny // isSunny has the value true
```

Logical AND Operator

The Logical AND Operator can be used when both values should be evaluated to true:

```let isCorrectPin = true
let isCorrectFaceID = false

if isCorrectPin && isCorrectFaceID {
print("Authentication successful!")
} else {
print("Authentication failed!")
}
```

Logical OR Operator

The Logical OR Operator can be used when either one value evaluates to true:

```if isCorrectPin || isCorrectFaceID {
print("Authentication successful!")
} else {
print("Authentication failed!")
}
```

Reference

https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html