Swift Foundation #1

Cover 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

Array

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

Control Flow

  • if-let-else
  • switch-case
  • while

Loops

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

Functions

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

Function as type, closure

  • (Int) -> Bool
  • Array has many methods that accepts closure

Swift Playground