3 Methods for Communicating Between Classes in Swift 5

func downloadData() { let data = "Network request information.

" delegate?.

didReceiveData(data) }}Now create an instance of Model in its Controller class and assign its delegate to self.

class ViewController: UIViewController { let model = Model() override func viewDidLoad() { super.

viewDidLoad() model.

delegate = self model.

downloadData() }}extension ViewController: ModelDelegate { func didReceiveData(_ data: String) { print(data) }}In order to assign the model’s delegate to self (self = the ViewController class in this example) the ViewController must conform to the ModelDelegate protocol.

We can achieve this by adding an extension of view controller that adopts the protocol in order to conform to the layout defined in ModelDelegate.

In this example, the ViewController holds an instance of a Model.

Once the model has successfully downloaded data it will call the function “didReceiveData” inside the ViewController.

Once this function has been called you can update your View class within the ViewController.

CallbacksCallbacks are simple to set up.

I don’t often use them as I prefer the rigidity of the delegation pattern.

However, they are useful for simple communication.

In a View class we have a function that runs an animation.

Upon the completion of the animation we want to alert our ViewController that the animation has finished.

class View { func runAnimation(completion: @escaping() -> ()) { //run animation, upon completion send callback completion() }}In the ViewController create an instance of the View class and call the runAnimation() function:Take special note of the “[weak self] in” inside the closure on runAnimation().

By specifying that self is a weak reference, we avoid retain cycles.

If we capture self strongly then the closure would hold a strong reference to self, thus not allowing deallocation in memory.

It is also possible to send data directly through a callback:Note: the underscore within a function definition means that we do not need to include the parameter name when calling a method.

Hopefully this article helped you learn more about some of the communication options available in Swift.

I often find myself using several of these methods inside a single project, as they each have their use-cases.

I use delegates for rigid layouts between classes that do lots of communicating.

I use Callbacks for simple functions that need to send a callback upon the completion of an action.

I use Notifications when I need to alert multiple classes to a new data download or change.

If you need any help feel free to email me at shrader.


com!.. More details

Leave a Reply