Show Menu
Cheatography

swift 4 Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Function

typealias operation = (Int, Int) -> (Int)

// parameters: constant (pass by value)
// want to modify?
func modifyParams(_ value: inout Int) {}
var value = 1
modifyParams(&value)

// overloading external parameter names
func multipleOf(_ multiplier: Int, and value: Int) {}
func multipleOf(multiplier: Int, value: Int) {}

// overloading return value
func getValue() -> Int
func getValue() -> String
let value: Int = getValue()

Basic types

// Range
let range1 = 0...2
let range2 = 0..<2

// Array
let arr1: [Int] = [1,2,3]
let arr2: Array<Int> = [1,2,3]

arr.first //=> Optional
arr[0] //=> value (maybe crash if wrong index)

arr[0...2] = [1,2,3]
arr[0...2] = [1,2,3,4,5] // still works

for item in arr {}
for (index, item) in arr.enumerated() {}

// Dictionary
let dic [String: Int] = ["alpha": 1, "beta": 2]
let dic Dictionary<String, Int>

dic["unknow"] //=> nil

for (key, value) in dic {}
for key in dic.keys {}

// Set
let set: Set<Int> = [1,2,3]

// Closure
var addClosure: (Int, Int) -> Int
// long form
addClosure = { (a: Int, b: Int) -> Int in
  return a + b
}
// short form use type inference
addClosure = { (a, b) in 
  return a + b
}
// even shorter     $0 = a, $1 = b
addClosure = {
  return $0 + $1
}
// shortest - omit "return" if immediately return
addClosure = {
  $0 + $1
}

// when closure is the last parameter
// common syntax
arr.filter { item -> Bool in
  return !!item
}
var stock = [1.5: 5, 2.5: 10]
let sum = stock.reduce(0) { result, pair -> Double in 
  return result + (pair.key * Double(pair.value))
}
 

Optional

// either value or nil
var optional: String?

// some func return optional
var parseInt = Int("1")                         // 1
var parseInt = Int("something ugly")   // nil

// maybe surprise
var optInt: Int? = 10
print(optInt) // Optional(10)
optInt + 1    // error. Must be unwrapped

// Avoid
// unwrapped with !
var unwrappedOptInt = optInt! // 1 or crash if optInt == nil

// Use this
// optional binding
if let unwrappedOptInt = optInt {} else {}

// can shadow like this (temporary access)
if let optInt = optInt {} else {}

// multiple unwrap
if let optInt = optInt, let optStr = optStr {}

// (better) use guard
// also better for optimization <- don't know why. find out later
let optFunc: () -> Int?
func takeMeIn() {
  guard let optFunc = optFunc() else {
     // when optFunc is nil
     return // guard must be returned or throw
  }
  // when optFunc is Int
}

// Nil Coalescing
let result = optInt ?? 0