# Basic Operators in Swift

Swift support most standard C operators and improves several capabilities to eliminate common coding errors. The assignment operator (`=`

) does not return a value, to prevent it from being mistakenly used when the equal to operator (`==`

) is intended.

Swift also provide range operators that are not found in C, such as `a..<b`

and `a..b`

as a shortcut for expressing a range of values.

**Terminology**

Operators are unary, binary, or ternary:**Unary: **Unary operators operate on a single target (such as `-a, !b, c!`

).**Binary: **Binary operators operate on two targets (such as `2 + 3`

).**Ternary: **Ternary operators operate on three targets. Like C, Swift has only one ternary operator, the ternary conditional operator (`a ? b : c`

).

# Assignment Operator

The assignment* *operator (`a = b`

) initializes or updates the value of `a`

with the value of `b`

:

let b = 10

var a = 5

a = b

// a is now equal to 10let (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

`if x = y {`

// This is not valid, because x = y does not return a value.

}

**Arithmetic Operators**

Swift support the four standard arithmetic operators for all numbers type

1. Addition `(+)`

2. Subtraction `(-)`

3. Multiplication `(*)`

4. Division `(/)`

1. 1 + 2 // equals 32. 5 - 3 // equals 23. 2 * 3 // equals 64. 10.0 / 2.5 // equals 4.0

Unlike the arithmetic operators in C and Objective-C, the Swift arithmetic operators do not allow values to overflow by default (such as `a &+ b`

)

# Remainder Operators

The remainder operator (`a % b`

) works out how many multiples of `b`

will be fit inside `a`

and returns the value that is left over knowns as the remainder.

Here’s how the remainder operators works, to calculate `9 % 4`

, you first work out how many `4s`

will fit inside `9`

. You can fit two`4s`

inside `9`

, and the remainder is `1`

.

`9 % 4 // equals 1 `

# Compound Assignment Operators

Like C, Swift provides *compound assignment operators* that combine assignment (`=`

) with another operation.

`var a = 1`

a += 2

// a is now equal to 3

# Comparison Operators

Swift supports all standard C comparison operators:

1. Equal to (`a == b`

)

2. Not equal to (`a != b`

)

3. Greater than (`a > b`

)

4. Less than (`a < b`

)

5. Greater than or equal to (`a >= b`

)

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

3. 2 > 1 // true because 2 is greater than 1

4. 1 < 2 // true because 1 is less than 2

5. 1 >= 1 // true because 1 is greater than or equal to 1

6. 2 <= 1 // false because 2 is not less than or equal to 1

Tuples are compared from left to right, one value at a time, until the comparison finds two values that are not equal. Those two values are compared and the result of that comparison determines the overall result of the tuple comparison. If all are equal then the tuples themselves are equal.

(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

It is special operator with three parts, which takes the form question ? answer1 : answer2.

The ternary conditional operator is shorthand for the code bellow:

`if question {`

answer1

} else {

answer2

}

# Nil-Coalescing Operator

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`

. The expression `a`

is always of an optional type. The expression `b`

must match the type that is stored inside `a`

.

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

`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 color = “red”

let name : String?var colorName = name ?? color

// name is nil, so colorName is set to the default of red

# 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 `a`

to `b`

, and includes the values a and b. The value of `a`

must not be greater than `b`

. The closed range operator is useful when iterating over a range in which you want all of the values to be used, such as with a

`for`

-`in`

loop:`for index in 1...5 {`

print("\(index)")

}

// 1

// 2

// 3

// 4

// 5

**Half-Open Range Operator:**The half-open range operator (

`a..<b`

) defines a range that runs from `a`

to `b`

, but doesn’t include `b`

. It’s said to be half-open because it contains its first value, but not its final value.`let arr = [1, 2, 3, 4]`

for i in 0..<arr.count {

print(arr[i])

}

// 1

// 2

// 3

// 4

**One-Sided Range:**The closed range operator has an alternative form for ranges that continue as far as possible in one direction.

let names = [A, B, C, D]for name in names[2...] {

print(name)

}// C

// Dfor name in names[...2] {

print(name)

}// A

// B

// Cfor name in names[..<2] {

print(name)

}// A

// Blet range = ...5

range.contains(7) // false

range.contains(5) // true

range.contains(-1) // false

# Logical Operators

Logical operators modify or combine the Boolean logic values `true`

and `false`

. Swift supports the three standard logical operators found in C-based languages:

1. Logical NOT (`!a`

)

2. Logical AND (`a && b`

)

3. Logical OR (`a || b`

)

**Logical NOT Operator:**The

*logical NOT operator*(

`!a`

) inverts a Boolean value so that `true`

becomes `false`

, and `false`

becomes `true`

.let flag = false

if !flag {

print("ACCESS DENIED")

}// Prints ACCESS DENIED

# Logical AND Operator

The logical AND operator (`a && b`

) creates logical expressions where both values must be `true`

for the overall expression to also be `true`

.

If either value is `false`

, the overall expression will also be `false`

. In fact, if the first value is `false`

, the second value won’t even be evaluated, because it can’t possibly make the overall expression equate to `true`

. This is known as ** short-circuit evaluation**.

This example considers two `Bool`

values and only allows access if both values are `true`

:

let a = true

let b = falseif a && b {

print("Welcome")

} else {

print("ACCESS DENIED")

}// Prints ACCESS DENIED

# Logical OR Operator

You use it to create logical expressions in which only *one* of the two values has to be `true`

for the overall expression to be `true`

.

Like the Logical AND operator above, the Logical OR operator uses short-circuit evaluation to consider its expressions. If the left side of a Logical OR expression is `true`

, the right side is not evaluated, because it can’t change the outcome of the overall expression.

let a = false

let b = trueif a || b {

print("Welcome")

} else {

print("ACCESS DENIED")

}// Prints Welcome