Search code examples
iosswiftclassprotocols

Why protocol is better than class in swift?


By watching the video tutorial provided by Apple, it seems that swift is protocol-oriented programming langue and apple encourage programmers to use protocol than class. But from my personal view, I see no apparent advantages for protocol. class can conform to protocol, but they can also inherit from superclass. We can add extension to protocol, but we can also add extension to class. We can implement functions in classes which conforms to protocol, but we can also override func in subclass. I am still confused that why we need to use protocol rather than class. And when we should use protocol instead of class ?


Solution

  • Lets take a downloading example.

    You have a Base class FileDownloadModel, and have 3 subclasses AudioFileDownloadModel, VideoFileDownloadModel, and ImageDownloadModel.

    You have a DownloadManager that takes a FileDownloadModel input and uses this model's urlToDownload property to download the file.

    Later down the line you are told that there is one more model coming but it's of type UserDownloadModel which is a subclass of User, and not FileDownloadModel.

    See now it becomes difficult to handle this scenario where you will have to change a lot of code to incorporate downloading methods.

    How protocol oriented programming will help you here:

    1. Create a protocol named DownloadingFileProtocol and add methods and properties that you need for downloading a file. eg. urlToDownload, pathToSave, extension etc.
    2. Implement the same protocol in FileDownloadModel and UserDownloadModel. The benefit here is that you don't have to change a lot of code in UserDownloadModel. You will just implement the methods from the DownloadingFileProtocol.
    3. If a new entity comes down the line again, you will not change any code. Rather, you'll just implement the protocol methods.
    4. And now your DownloadManager can take a DownloadingFileProtocol as input instead of a specific model. As well, you can now make any model "downloadable" by having it adopt this protocol.