Why is a protocol better than a class in fast?

Watching Apple's video tutorial, it seems that langue and apple are quick programmers to encourage programmers to use the protocol than the class. But, in my personal opinion, I do not see obvious advantages for the protocol. a class can conform to the protocol, but they can also inherit from a superclass. We can add an extension to the protocol, but we can also add an extension to the class. We can implement functions in classes that conform to the protocol, but we can also override func in a subclass. I am still confused that we need to use a protocol, not a class. And when should we use the protocol instead of the class?

+10
ios class swift protocols
source share
4 answers

Let's look at a boot example.

You have the base class FileDownloadModel and 3 subclasses of AudioFileDownloadModel, VideoFileDownloadModel and ImageDownloadModel .

You have a DownloadManager that accepts FileDownloadModel input and uses this urlToDownload model to download the file.

You will be informed later that there is another model, but it is of type UserDownloadModel, which is a subclass of the user , not FileDownloadModel .

You see, now it becomes difficult to handle this scenario when you have to change a lot of code to enable loading methods.

How protocol-oriented programming will help you here:

  1. Create a protocol called DownloadingFileProtocol and add the methods and properties needed to download the file. eg. urlToDownload, pathToSave, extension, etc.
  2. Implement the same protocol in FileDownloadModel and UserDownloadModel . The advantage here is that you do not need to change a lot of code in UserDownloadModel . You simply implement the methods from DownloadingFileProtocol .
  3. If the new entity reappears on the line, you will not change any code. Rather, you just implement protocol methods.
  4. And now your DownloadManager can take DownloadingFileProtocol as input instead of a specific model. In addition, you can now make any model โ€œbootableโ€ by adopting this protocol.
+8
source share

class and protocol are orthogonal concepts. The protocol traverses the class tree and combines one or more classes with a disparate family tree.

Perhaps easier:

  • "class" defines what an object is.
  • "protocol" defines the behavior of the object.

So you have a Car class:

class Car { var bodyStyle : String } 

and grade color:

 class Color { var red : Int var green : Int var blue : Int } 

Now, it is more or less obvious that Colors and Cars are completely unrelated, however, suppose I want to be able to easily convert one of the strings to Strings, so I can debug with:

 print(Car(...)) 

or

 print(Color(...)) 

For this purpose, the Swift language defines the CustomStringConvertible protocol, so we can declare that a Car can be printed using this protocol:

 extension Car : CustomStringConvertible { var description : String { get { return "Car: \(bodyStyle)" } } } 

and color:

 extension Color : CustomStringConvertible { var description : String { get { return "Color: \(red) \(green) \(blue)" } } } 

So, before I needed one printing method for each class, now I need only one printing method, which looks something like this:

 func print(data:CustomStringConvertible) { let string = data.description ... bunch of code to actually print the line } 

This is possible because declaring that the class implements the protocol is a promise to use the methods from the protocol, knowing that they are implemented and (presumably) doing what was expected.

+12
source share

This is largely a type hierarchy. Suppose you have an object representing a GlowingRedCube , but you want this type to be used in a variety of common codes that concern:

  • Various Shapes - Cube extends Shape
  • Various colors - Red extends Colorful
  • Different types of lighting - Glowing extends Illuminated

Have you got any problems. You can choose a base class and add specializations: GlowingRedCube extends GlowingCube extends Shape , but then you get a very wide set of classes and an inflexible set of things (what if you want to make SoftRedCube , but save any methods that you defined for your existing type red cube?)

You can just have a Cube and have lighting and shape properties, but then you wonโ€™t get a good compiler type check: if you have the Room.lightUp() method and need to pass it to Cube , then you need to check whether this type includes any lighting ! If you can only pass it Illuminated , then the compiler will stop you as soon as you try.

Protocols allow you to separate this: GlowingRedCube can implement the Illuminated protocol, the Colorful protocol, and the Shape protocol. Due to protocol extensions, you can enable functionality by default, so you do not need to select a hierarchy level to join it.

 struct GlowingRedCube: Shape, Colorful, Illuminated { // .. } 

Effectively, protocols allow you to attach behavior to an object, regardless of what else this object does. That's why they are used for things like delegate protocols and data sources: even if you basically bind these things to the ViewController , the underlying object doesn't matter, so you can be flexible about how you implement it.

Swift uses the Swift protocol much more than just the basics: they are extremely powerful because they can be tied to several different code constructs: classes, structures, and enumerations. This allows you to really get closer to the programming protocol. There was a great video about this approach from WWDC last year , but it helps to spend some time trying some different object structures to get a feel for the problems first.

+3
source share

With protocols, one class / structure can be used as different things. For example, the String structure conforms to soooo many protocols!

 Comparable CustomDebugStringConvertible Equatable ExtendedGraphemeClusterLiteralConvertible Hashable MirrorPathType OutputStreamType Streamable StringInterpolationConvertible StringLiteralConvertible UnicodeScalarLiteralConvertible 

This means that String can be used as 11 different things! If one of the above protocols requires a method as a parameter, you can pass a string.

"But I can just create a class of gods that has all the methods that have protocols!" you claimed. Remember that you can only inherit one class from Swift, and multiple inheritance is so dangerous that it can make your code super complicated.

In addition, with the help of protocols you can define your custom class behavior. String hashcode method is different from the Int method. But they are both compatible with this function:

 func doStuff(x: Hashable) { } 

This is a true miracle of protocols.

Last but not least, protocols make sense. Protocols are a "kind" or "can be used as a" relationship. When X can be used as Y, it makes sense that X conforms to the Y protocol, right?

+1
source share

All Articles