Work

Blog

About

Resume

Vin Bui's Logo

Work

Blog

About

Resume

Operators

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
Basic operators

The following lines are equivalent:

Basic operators

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 .

Basic operators error

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 .

Type casting

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.

Modulus operator

Common Operators

The following is a list of common operators that we are likely to use.

Common operators

String Interpolation

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)."
String interpolation

Of course, we could have used the + operator to concatenate these strings together.

Add operator instead of string interpolation

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 .

Add operator instead of string interpolation error

We could cast age to a String but that would be expensive.

Casting instead of string interpolation

Using string interpolation is a lot more efficient and looks cleaner too!

Using  string interpolation

Data Types

Operators

Image of VinBot

VinBot

Hi!

I’m VinBot. An AI assistant here to answer your questions about Vin Bui's portfolio.

How can I help you today?

Let's turn your ideas
into reality!

Unleash our creativity and make something extraordinary happen. Send me a message and let's explore the possibilities.

Designed and developed by Vin © 2024

Designed and developed by Vin © 2024