Communicating Between Classes Swift

print
  1. Notifications
  2. Delegation
  3. Callbacks

Notifications

NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: .didReceiveData, object: nil)

@objc func onDidReceiveData(_ notification:Notification) {
    // Do something now
}
Observer
NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: .didReceiveData, object: nil)

Delegation

protocol ModelDelegate: class {
    func didReceiveData(_ data: String)
}

Callbacks

func getBoolValue(number : Int, completion: (result: Bool)->()) {
    if number > 5 {
        completion(result: true)
    } else {
        completion(result: false)
    }
}

getBoolValue(8) { (result) -> () in
    // do stuff with the result
    print(result)
}
Important to understand:

(String)->() // takes a String returns void
()->(String)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.