# Swift Operators

> A guide to Swift operators, covering the assignment, arithmetic, compound assignment, comparison, range, and logical operators you use to work with values.

Author: Flavio Copes | Published: 2021-05-21 | Canonical: https://flaviocopes.com/swift-operators/

> This tutorial belongs to the [Swift](https://flaviocopes.com/swift-introduction/) series

We can use a wide set of operators to operate on values.

We can divide operators in many categories. The first is the number of targets: 1 for **unary operators**, 2 for **binary operators** or 3 for the one and only **ternary operator**.

Then we can divide operators based on the kind of operation they perform: 

- assignment operator
- arithmetic operators
- compound assignment operators
- comparison operators
- range operators
- logical operators

plus some more advanced ones, including nil-coalescing, ternary conditional, overflow, bitwise and pointwise operators.

> Note: Swift allows you to create your own operators and define how operators work on your types you define.

### Assignment operator

The assignment operator is used to assign a value to a variable:

```swift
var age = 8
```

Or to assign a variable value to another variable:

```swift
var age = 8
var another = age
```

### Arithmetic operators

Swift has a number of binary arithmetic operators: `+`, `-`, `*`, `/` (division), `%` (remainder):

```swift
1 + 1 //2
2 - 1 //1
2 * 2 //4
4 / 2 //2
4 % 3 //1
4 % 2 //0
```

`-` also works as a unary minus operator:

```swift
let hotTemperature = 20
let freezingTemperature = -20
```

`+` is also used to concatenate String values:

```swift
"Roger" + " is a good dog"
```

### Compound assignment operators

The compound assignment operators combine the assignment operator with arithmetic operators:

- `+=` 
- `-=`
- `*=`
- `/=`
- `%=`

Example:

```swift
var age = 8
age += 1
```

### Comparison operators

Swift defines a few comparison operators:

- `==`
- `!=`
- `>`
- `<`
- `>=`
- `<=`

You can use those operators to get a boolean value (`true` or `false`) depending on the result:

```swift
let a = 1
let b = 2

a == b //false
a != b //true
a > b // false
a <= b //true
```

### Range operators

Range operators are used in loops. They allow us to define a range:

```swift
0...3 //4 times
0..<3 //3 times

0...count //"count" times
0..<count //"count-1" times
```

Here's a sample usage:

```swift
let count = 3
for i in 0...count {
  //loop body
}
```

### Logical operators

Swift gives us the following logical operators:

- `!`, the unary operator NOT
- `&&`, the binary operator AND
- `||`, the binary operator OR

Sample usage:

```swift
let condition1 = true
let condition2 = false

!condition1 //false

condition1 && condition2 //false
condition1 || condition2 //true
```

Those are mostly used in the `if` conditional expression evaluation:

```swift
if condition1 && condition2 {
  //if body
}
```
