Swift

print() and Operators

Combining and manipulating different data types

print()

So far, we can see all of our variable values on the right side, regardless of their type. However, sometimes we want to show more, and do that, we will use the print function. To use it, we just have to put it around what we want to print.

print("I just printed something!")
var name = "Greg Heffley"
print(name)
    
var age = 27
print(age)

Now, when we run the code, we can see a bottom panel popup that shows both of these values.

Merging Variables and Information

Now, what if we want to show both of these in the same sentence? There are a few ways to do this, and the best way is to surround variables in \(), like so:

print("My name is \(name) and I am \(age) years old.")

The other way to do this is to concatenate everything:

print("My name is "+name+" and I am "+age+" years old.")

However, it isn’t as clean as we would like it to be.

Operators

We can also do basic math with our variables or with numbers in general, whether integers or floats. Just use ‘+’ for addition, ‘-’ for subtraction, ‘*’ for multiplication, and ‘/’ for division. Along with that, we can also manipulate the variables themselves.

var a  = 2
a = 4 + 2
a = 4 - 1
a = 4 * 3
a = 4 / 2

a += 8 // same as writing  a = a + 8
a -= 2 // same as writing  a = a - 2
a *= 3 // same as writing  a = a * 3
a /= 2 // same as writing  a = a / 2 

What you can also see above are // and then text afterwards. This is a comment. Comments are completely ignored in the code, and are meant to help you. All you have to do is type // then you can write whatever you want afterwards.

We can also use these within our variables when printing as well!

var number = 2
print("\(number) multiplied by 5 is \(number*5)!")

Modulo

There is another operator that you may not be familiar with, the modulo operation. What it does essentially, is it divides the numbers and returns the remainder. For this operation, we use the %. Here’s an example:

let a = 7
let b = 6
let c = 2
print("The remainder of \(a)/\(c) is \(a%c).") // remainder 1
print("The remainder of \(b)/\(c) is \(b%c).") // remainder 0    
chevron_up