Types and variable declarations

Swift supports two basic kinds of variable declarations, let and var. let is used to declare variables whose values will not change (similar to const variables in other languages), while var is used to declare variables whose values may change over time:

let PI : Double = 3.14159265
var x : Double = 3.5
PI = 22/7 // Illegal - PI is const
x = 4.5 // OK - x is var

Swift offers automatic type deduction: when you declare a variable and initialize it at the same time Swift can deduce the type of the variable from the value you use to initialize it. This makes the type declaration part of the variable declaration optional.

let greeting = "Hello, " // greeting is String
var name = "World" // name is String

Swift is a strongly typed language - once you have set the type for a variable you can not change it.

name = 42 // Illegal - name has type String

Strings

Swift uses string interpolation to insert values into strings using the \() construct.

let strOne = "Area is \(PI*x*x)"
let circumference = 2.0*PI*x
let strTwo = "Circumference is \(circumference)"

You can use + to concatenate strings.

let result = strOne + ". " + strTwo

Collection classes

Swift includes classes in its standard library for lists, sets, and dictionaries.

You can use an array literal to make a list in Swift.

var fruits = ["Apple","Banana","Cherry"]

Lists in Swift are always mutable.

fruits.append("Grape")
fruits.remove(at:2)

If you want to make a list immutable, declare it with let:

let people = ["Alice","Betty","Charlie"]

The following syntax allows you to make a Set from an array literal:

let setOfPeople : Set<String> = ["Alice","Betty","Charlie"]
let isBobPresent = setOfPeople.contains("Bob")

Swift uses this syntax to make a dictionary.

let pets : [String:String] = ["Alice":"Dog","Betty":"Cat","Charlie":"Dog"]

Once again, using val in place of let makes the dictionary mutable:

val cars : [String:String] = ["Alice":"Camry","Betty":"F150","Charlie":"Tesla"]
cars["David"] = "Prius"
cars["Betty"] = "Tundra"