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.
Swift Basics
Fall 2023
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.
1var a = 0
2a = a + 10
3a = a - 5
4a = a * a
5a = a / 10
The following lines are equivalent:
These operators are self-explanatory; however, if we were to look closer 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 new variables of type Double or Float since we cannot change its type once initialized. We would also need to make sure that the values in which we apply these operators on must also be Double or Float .
Let's 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 values 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.
String interpolation is a way of combining variables and constants inside a string. Take a look at this example:
1var name = "Vin"
2"My name is (name)."
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!
VinBot
Hi!
I’m VinBot. An AI assistant here to answer your questions about Vin Bui's portfolio.
How can I help you today?
Unleash our creativity and make something extraordinary happen. Send me a message and let's explore the possibilities.