Swift - Variable explicitly typed

Introduction

You can tell the compiler exactly what type you want the variable to be, making it explicitly typed:

let explicitInt  : Int = 5 
var explicitDouble  : Double = 5 
explicitDouble + 0.3 

Explicitly typed variables are allowed to initially have no value, but you need to assign a value to them before you try to access them:

var someVariable  : Int 
// this is an error 
// someVariable += 2 

// this works 
someVariable = 0 
someVariable += 2 

If you create a variable with no value, the only thing you can do with it is give it a value.

Swift doesn't require you to put a semicolon at the end of each line to indicate they have ended.

If you are missing them you can include them if you want.

You have to use semicolons when putting multiple statements on a single line.

var exampleInteger = 5; print(exampleInteger) 

You can break up your code over multiple lines without problem, like this:

var anotherExampleInt 
= 7 

Related Topic