Swift notes

Values

Use let to define constants.

Use var to define variables.

Type Casting

var firstName: String = "Michael"

After the variable name, use a colon (:), followed by the type, an equal and then the value.

Types cannot be mixed when being assigned to a value. A type conversion must be made before assigning.

let firstName = "Michael"
let age = 33
let nameAge = firstName + " is " + String(age) + " years old."

String Interpolation aka mixing variables in strings

let firstName = "Michael"
let statement = "\(firstName) likes to eat pizza."

To interpolate a variable in a string, use \(variable_name)

Arrays and Dictionaries

Both arrays and dictionaries use square brackets [].

Control Flow

  • Parentheses around conditions and loops are optional.
  • Braces around the block of a control are required.

for-in loop

for-in loops are used to iterate over dictionaries. Dictionaries are made up of key-value pairs:

key: value

In a for-in loop a pair of names are provided to the loop to use for each of the key-value pair.

for (key, value) in dictionary {
  print("\(key) \(value)")
}

Functions

Functions are defined by using func. Parameters are defined by this syntax parameterName: type. -> is used to separate the parameters for the return.

When defining the return, the type must be set:

func add(value1: Int, value2: Int) -> Int{
    return value1 + value2
}

When defining a function’s parameters a custom label could be assigned or you could use no argument label by using _.

func add(_ value1: Int, no2 value2: Int) -> Int{
  return value1 + value2
}

add(3, no2: 4)

Changelog

07-15-2016
Added section about Arrays and Dictionaries and Control Flow
07-16-2016
Added section about Functions and Closures