Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protocol vs Interface [duplicate]

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.

like image 949
Obsidian Phoenix Avatar asked Jun 04 '14 15:06

Obsidian Phoenix


People also ask

What is the difference between a protocol and an interface?

An interface defines how two entities may communicate. A protocol defines how they should communicate and what that communication means.

Can an interface have multiple methods?

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.

What do you mean by interface?

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.

How many communication protocols are there?

There are two types of communication protocols, based on their representation of the content being carried: text-based and binary.


1 Answers

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.

like image 86
Connor Avatar answered Sep 27 '22 23:09

Connor