An interface defines how two entities may communicate. A protocol defines how they should communicate and what that communication means.
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.
Protocols provide a blueprint for Methods, properties and other requirements functionality. It is just described as a methods or properties skeleton instead of implementation. Methods and properties implementation can further be done by defining classes, functions and enumerations.
Interfaces are same as protocol in Swift. class and struct both can implements the protocol .
Essentially protocols are very similar to Java interfaces except for:
protocol<A, B>
way of protocol composition. For example, declaring a function parameter that must adhere to protocol Named
and Aged
as: func wishHappyBirthday(to celebrator: Named & Aged) {}
These are the immediately apparent differences for a Java developer (or at least what I've spotted so far). There's more info here.
Complementing @Thomas Schar's answer. The Swift protocol magic comes from the extension.
One thing that got me scratching my head for a couple of hours is that not all protocols can be used as property types. For example, if you have a protocol with typealias, you cannot directly use it as a type of property (it makes sense when you think about it, but coming from Java we really want to have a property like userDao: IDao).
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