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 ?
You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create.
In Swift, value types are preferred over classes. However, object-oriented concepts don't work well with structs and enums: a struct cannot inherit from another struct, neither can an enum inherit from another enum. So inheritancefa - one of the fundamental object-oriented concepts - cannot be applied to value types.
In Swift, a protocol defines a blueprint of methods or properties that can then be adopted by classes (or any other types).
One protocol can inherit from another in a process known as protocol inheritance. Unlike with classes, you can inherit from multiple protocols at the same time before you add your own customizations on top. Now we can make new types conform to that single protocol rather than each of the three individual ones.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With