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.
1
2
|
let secondsInHour = 3600
var milesIDidToday = 24
|
Variables can be defined all in the same line:
1
|
var foo = 2, bar = 3, wow = 5, cat = 7
|
Type Annotation
Allows to specify what type of variable it is:
1
|
let nameOfCat: String = "Cat" // (String) type annotation
|
Multiple variables of the same type can be defined like this:
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
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
1
2
|
let name = "Slim Shaddy"
print("My name is \(name)")
|
this would print: My name is Slim Shaddy
1
|
// this is a single line comment
|
1
2
3
4
|
/*
this is a
multiline comment
*/
|
Integers
1
2
|
var doorNumber: Int = 85
var totalKeys = 4
|
Floats
6 digit precision
Double
15 digit precision
1
|
var longitude: Double = 5.34524
|
Explicit conversion
Float to Double
1
|
var doublePi = Double(pi)
|
Float to Int
1
|
var integerPi = Int(pi)
|
Boolean
1
2
|
var isWalking = true
var canCode: Bool = false
|