So I came across the subject of protocols and I have searched the internet a bunch for an answer but I couldn't find one, atleast one that solved my problem.
So I understand that Protocols are a "blueprint" of methods, properties and such and that it can be implemented in a class or struct and that it needs to conform to its requirements and such, but why would one use one?
I mean you could also just create a function inside a struct itself. It seems a bit of a hassle to write a protocol and then for the implementation of said protocol you would have to write all the requirements again with more code this time.
Is there a particular reason why one would use a protocol? Is it for safety of your code or some other reason?
For example:
In swift you have the CustomStringConvertible protocol which has a required computed property to control how custom types are represented as a printable String value, but you could also create a function inside your class which could solve this issue aswel. You could even have computed property which does the same as this protocol without even implementing this protocol.
So if someone could please shed some light onto this subject, that would be great.
Thank you in advance!
Protocolsin swift are similar toAbstractionsin some other languages.before answering your question, we have to clear things out,
Protocolsdeclaration could be various but considering you have already read tons of it,It will also be great to mention this answer here.
Now lets get into the real use case here.
Consider you have this protocol.
Now we need some type of
structsorclassesto confirm to it, or Multiple ones.And here where it lays one of the biggest benefit of it.
Consider you have to print the
namepropriety of an objects.For example those.
You would simply type this without
ProtocolsWhich is correct, now observe the code below using protocol
Printable.It only takes us one
funcand so on using theProtocols.Conclusion
You can also read more about them here.
And more about the use cases here.