Swift Tutorial: Introduction 07 - Variables: Type Safety and Casting

Written by Paul Napier on . Posted in Swift Tutorials: Introduction

Hello everyone and welcome to the seventh lesson in swift programming brought to you by MadApper. My name is Paul Napier and in today's lesson I thought it would be a good time to run you through type safety.

Just like Objective C and Java, Swift is a type safe language. This means that it helps to prevent errors in your code by encouraging you to be specific about variable types, so you can't pass the wrong value type.

So what does this mean? Well let's take three variables:

var myInteger:Int = 10
var myFloat:Float = 5.5
var myDouble = 2.75

Now if I try to reassign my double or float variables with a new number, there is no problem. However, if I try to assign a floating point number to the integer, I receive a type error. Likewise if I try to assign these variables to each other I will get the same error. This type safety, although a very useful feature of the language, can cause issues especially if you are allowing the compiler to implicitly define some of your variables.

It's common in code that you will want to perform mathematical functions with your numerical variables. So you can see that it will cause a problem if I cannot use integers with floats or floats with doubles. This is where casting comes in.

You will come across casting a lot when programming, and this is the simplest example of it.

Let's do a very basic calculation with these variables.

var result:Float = myInteger + myDouble - myFloat

As you can see I have an error. Now I happen to have explicitly defined my result variable as a float, so therefore I am going to have to do a little work to get that. And it's as simple as writing Float(variable) and that's it! Let's try it here:

var result:Float = Float(myInteger) + Float(myDouble) - myFloat

And hey presto we have a result!

So that is type safety and casting. Bear in mind casting does not work on every type, and this is only a basic example. In the next tutorial we are going to cover Booleans. 

Add comment

Security code