The original article – Understanding Delegates and Delegation in Swift 4 was published on appcoda.com.
[Download Xcode 9 project with full Swift 4 source from GitHub.]
Introduction
I’m going to talk about “delegates” and “delegation.” I’ll lead you through a simple example of implementing the delegation design pattern in Swift 4, with full source code. My intent here is to show you how delegation works without getting bogged down in some crazy complex example. To help you become the best of the best, I’m going to introduce you to one of the greatest design tools to aid in object-oriented software development, UML. I’ll show you a UML diagram that I drew up to design and document the implementation of the delegation design pattern used in the sample app we’ll build together. Download the Xcode 9 project with full Swift 4 source from GitHub to follow along.
I’ll show you how to build a user interface (UI) helper, a class that downloads a file at a specified URL. Most importantly, I’ll show you how, through delegation, a UIViewController
subclass can be notified by the helper that an image file has finished downloading, and then the view controller can display the image on screen. For the sake of simplicity and clarity, we’ll pretend that Swift has minimal support for downloading a file from a URL. We’ll manually wire up the notification that the file has finished downloading using the delegation design pattern. Here’s the app we’ll build:
Continue reading “Tutorial: delegates and delegation in Swift 4”