Capture list/value

Notes from Capturing Values In Swift Closures

Within a closure, referring to variables outside of the closure, strong references are created.

class MyClass {
let a = 1
let myClosure = {
print(self.a)
}
myClosure() // 1
a = 2
myClosure() // 2
}

If we don’t want the strong ref, we can specify weak

class MyClass {
let a = 1
let myClosure = { [weak self] in
guard let strongSelf = self else { return }
print(strongSelf.a)
}
myClosure() // 1
a = 2
myClosure() // 1 <-- here's the difference
}

Dispatch Queues

What? A queue that runs tasks FIFO.

Types? 

  • Serial – one at a time
    • system-provided: main queue
    • you can create your own
  • Concurrent – 1+ tasks at a time
    • system-provided: 4 queues (high, default, low, and background)
    • you can create your own, but 4 system ones should be good enough
Note: iOS 8+ should use QoS instead. 

    KVO

    Notify objects when changes to properties of other objects. Very similar to willSet and didSet, but they can be defined outside of the type defination.

    observation = observe(
    \.objectToObserve.myDate,
    options: [.old, .new]
    ) { object, change in
    print("myDate changed from: \(change.oldValue!), updated to: \(change.newValue!)")
    }