I've been reading the swift documentation, and working through the playground. I have to admit I have zero knowledge of Objective-C/iOS development (outside of Xamarin at least). To my eyes, a protocol seemed identical to the C# interface.
However, I noticed whilst looking around on the web that Objective-C has a concept of both a protocol (source) and an interface (although I'm not really sure what the difference is). Swift doesn't seem to have both - just protocols.
Could someone explain, for swift, what the difference/relationship between a Protocol and a C# interface is?
Update: I appreciate that the answer might be functionally the same as the duplicates listed, but I think that, given that this is asking about a different language, that the question still has merit in it's own right. After all, new developers to swift might have no knowledge of Java (beyond Javascript, I have none). Placing an expectation on someone to have knowledge of a totally different language system in order to have the answer to their question is a bit much, isn't it!? This discussion on meta is also discussing this issue.
An interface defines how two entities may communicate. A protocol defines how they should communicate and what that communication means.
Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. An interface can contain any number of methods.
Think of an interface as a "face-to-face," a place where things, or people, or people and things (like you and your computer) meet. Any common boundary or area of convergence can be an interface. Used as a verb, interface means to merge or mingle, bonding and synthesizing by communicating and working together.
There are two types of communication protocols, based on their representation of the content being carried: text-based and binary.
Objective C protocols serve basically the same purpose as interfaces in Java/ C#. Objective C interface files are different. Like C, Objective C has interface files that publicly declare the methods and properties of a class, that are then implemented in an implementation file. For example you may have an interface file of a class that looks something like this:
@interface
-(void)myMethod;
@end
then in your implementation file you actually implement the method:
-(void)myMethod{
//code
}
Swift does away with separate interface and implementation files. So it only has protocols.
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