Start with Swift: – 03: Operators

Welcome to Start with Swift! This is a “series” of articles to get to know the basics of the Swift programming language. Want to start programming? Swift is an ideal choice to start with because it is expressive and easy to understand.

Now let’s get started. This part is more “math” focused, but you don’t have to be worried, it’s just more about logic. So let’s look at operators and their usage in coding.

Arithmetic operators

When we need to use math operations (eg. to create a countdown) we use operators just like we’ve been taught in math lessons (+, -, * and /). Let’s look how we can convert hours into seconds

let second = 1
let minute = second * 60
let hour = second * 3600

The constant “second” is set to 1. If we want to get 1 minute, we simply multiply “second” by 60, because we know that 1 minute = 60 seconds. When it comes to hours, you can either multiply “second” by 3600 or multiply “minute” by 60.

Next, we have remainders (%). They calculate how many times one number can fit inside another, then sends back the value that’s left.

let number = 4
let remainder = 13%number

If the number is set to 4, we will get back 1 from this code. Number 4 fits into 13 three times with the remainder 1.

Overloading

Overloading is used when we want to load more values at once.

let age = 7
let doubleAge = 7+7

let animal = "dog"
let action = animal + "barks"

Comparisons

Used to compare values. Get to know the syntax:

== …. equals

!= …. not equals

<,> …. less than, more than

<=, >= …. less or equal, more or equal

Range operators

We use range operators to fit value(s) into a specific range. If we use a number, that is out of a specific range, Swift will crash with an error “Index out of range”.

1..<5

This range contains these numbers: 1, 2, 3 and 4.

1...5

This range contains these numbers: 1, 2, 3, 4 and 5.

Ternary operators

Ternary operators work with 3 values at once. It exists, but it’s rarely used.

let firstNumber = 11
let secondNumber = 16
print(firstNumber == secondNumber ? "Numbers are the same" : "Numbers are different")

The “?” in this code checks, whether the numbers are the same. In this case, the output would be “Numbers are different”.