Declare a new variable with var
, followed by a name, type, and value:
var num: Int = 10
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:
let ten = 10 // num is an Int
let pi = 3.14 // pi is a Double
let floatPi: Float = 3.14 // floatPi is a Float
Variable names aren't restricted to letters and numbers - they can also contain most other unicode characters, although there are some restrictions
Constant and variable names cannot contain whitespace characters, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters. Nor can they begin with a number
Source developer.apple.com
var π: Double = 3.14159
var 🍎🍏: String = "Apples"