Creating a Variable

Declare a new variable with var, followed by a name, type, and value:

var num: Int = 10
var str: String = "Hello World!"

Variables can have their values changed:
num = 20 // num now equals 20

Unless they’re defined with let:
let num: Int = 10 // num cannot change

Swift infers the type of variable, so you don’t always have to declare variable type:
var ten = 10 // num is an Int
var txt = "Hello!" // text is a String
var pi = 3.14 // pi is a Double
var floatPi: Float = 3.14 // floatPi is a Float

Leave a Reply

Your email address will not be published. Required fields are marked *