3️⃣Operators
Fall 2023 | Vin Bui
Last updated
Fall 2023 | Vin Bui
Last updated
We have seen the four basic math operations in elementary school: addition, subtraction, multiplication, and division. In Swift, we can use operators to perform these operations.
The following lines are equivalent:
These operators are self-explanatory; however, if we were to take a closer look at the the line a = a / 10
we can notice that the output is 2
instead of 2.5
. The reason for this is because the type of a
is an Int
. If we were to perform these operations on a
, then we must also use an Int
.
Then, how do we get the value 2.5
? Because the type of a
is an Int
, then we must introduce a new variable of type Double
or Float
since we cannot change the type of a variable once initialized. We would also need to make sure that the values in which we apply these operators on must also be a Double
or Float
.
Let's take a look at the line Double(a)
. This is known as type casting. Because a
is an Int
and we needed a Double
, Double(a)
converts the value 2
to 2.0
. Note that this does not change the type of a
. It only produces a value to be used for that operation.
One more common operator we may see is the modulus operator (%
). This is similar to the /
operator except we return the remainder.
The following is a list of common operators that we are likely to use.
| greater than |
| or |
| greater than or equal to |
| and |
| less than |
| not |
| less than or equal to | ||
| equal to | ||
| not equal to |
String interpolation is a way of combining variables and constants inside a string. Take a look at this example:
Of course, we could have used the +
operator to concatenate these strings together.
The problem with this approach is efficiency especially if we want to concatenate multiple variables. Another issue with using +
is that Swift does not allow types such as Int
or Float
to be glued with a String
.
We could cast age
to a String
but that would be expensive.
Using string interpolation is a lot more efficient and looks cleaner too!