Swift Foundation #1

variables, types, array, condition, function

Declare simple value

  • let is constant
  • var is mutable variable

Primitive Types

let i = 42 // An Int type

let s = "hello" // A String type

let s2: String = "Declare with explicit type"

Shorthand = less code

Class & Struct

  • Create your own type using class or struct
struct Person {
    let name: String
    let birthYear: Int
}

let alice = Person(...) // alice is an instance 

Class vs Struct

  • Reference type vs Value type
  • Struct will be copied when passed or assigned
  • Struct property needs to state mutability
  • Use struct for data model
  • Class are passed by "pointers" reference
  • Class has inheritance (object oriented programming)

Enum

  • A simple type with certain known enumerations
enum Direction {
    case up, down, left, right
}

Array

  • The simplest and most widely used collection type
  • Others are dictionary, set

Control Flow

  • if-then-else
  • switch-case
  • while

Loops

  • for item in array
  • for i in 0..<10

Functions

  • Operation with input and output
  • Named function with func
func isEven(num: Int) -> Bool {
    ...
}

Function as type, closure

  • Function can be nameless
  • (Int) -> Bool is a signature with input Int & output Bool
  • Array has many methods that accepts closure eg. map(...)

Swift Playground

Play around with code 🛝