Swift variables

Types of variables

Swift has 2 types of variables let and var.

  • let defines constants. Cannot be changed over time.
  • var defines any other variable type that can change over time.

variables.swift
1
2
let secondsInHour = 3600
var milesIDidToday = 24

Variables can be defined all in the same line:

variablesInline.swift
1
var foo = 2, bar = 3, wow = 5, cat = 7

Type Annotation

Allows to specify what type of variable it is:

typeAnnotation.swift
1
let nameOfCat: String = "Cat" // (String) type annotation

Multiple variables of the same type can be defined like this:

multiple.swift
1
let firstPersonName, lastPersonName: String

Type Inference

Allows the user not to have to define the type of variable and allows the compiler to make that decision

inference.swift
1
var foo = 15

The compiler inferes that the type of foo is integer


Swift strings

String Interpolation

String interpolation allows to join (concatenate) several strings and variables together

interpolation.swift
1
2
let name = "Slim Shaddy"
print("My name is \(name)")

this would print: My name is Slim Shaddy


Comments

singleLineComment.swift
1
// this is a single line comment
multilineComment.swift
1
2
3
4
/*
this is a
multiline comment
*/

Integers

integers.swift
1
2
var doorNumber: Int = 85
var totalKeys = 4

Floats

6 digit precision

floats.swift
1
var pi: Float = 3.14

Double

15 digit precision

doubles.swift
1
var longitude: Double = 5.34524

Explicit conversion

Float to Double

convertionFloatDouble.swift
1
var doublePi = Double(pi)

Float to Int

conversionFloatInt.swift
1
var integerPi = Int(pi)

Boolean

boolean.swift
1
2
var isWalking = true
var canCode: Bool = false