193

I'm going through the iOS tutorial from Apple developer page.

It seems to me that protocol and interface almost have the same functionality.

  • Are there any differences between the two?

  • the different usage in the project?

Updated

Yes, I did read the link above and I'm still not sure what the differences and usage between protocol and interface. When I ask a question like this, I would like to see a simple explanation about the topic. Sometime it could be tough to get everything from the documentation.

Yoon5oo
  • 496
  • 5
  • 11
Bun
  • 3,037
  • 3
  • 19
  • 29
  • 1
    Protocols in Swift and Interfaces in Java are same concepts. See [here](https://en.wikipedia.org/wiki/Protocol_(object-oriented_programming)) – Vivek Molkar Jun 16 '15 at 05:50
  • 90
    I think questions like this one about differences between languages are really useful for understanding language features. And I don't think they lead to unnecessary opinionated answers nor are very easy to find the answer to in documentation. So I don't think the down votes on this question are justified. – Lii Jun 16 '15 at 06:31
  • 1
    Here's a couple of **critical real-world points** about Java interfaces - http://stackoverflow.com/a/41143492/294884 - that would be key for anyone **fresh with Swift, trying Java** – Fattie Feb 24 '17 at 13:16
  • In the other direction, it's woprth remembering that ***the entire raison d'etre*** of Swift is that it is for "protocol oriented programming". You do everything with "protocol extensions" in Swift ubiquitously. For example [here](http://stackoverflow.com/questions/41796998/protocol-extension-doesnt-seem-to-enforce-variable-in-consumer) is a subtle issue about Swift (ie: "about protocol extensions") which illustrates some of the issues. – Fattie Feb 24 '17 at 13:36
  • 3
    In Swift, instead of interfaces, the protocol name is used because in Objective C header files (useless duplicates) from C are called interfaces – Alex78191 Apr 29 '18 at 23:21

3 Answers3

156

Essentially protocols are very similar to Java interfaces except for:

  • Swift protocols can also specify properties that must be implemented (i.e. fields)
  • Swift protocols need to deal with value/reference through the use of the mutating keyword (because protocols can be implemented by structures, enumerations or classes).
  • you can combine protocols at any point using "Protocol Composition". This replaces the older swift 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.

Ben Butterworth
  • 22,056
  • 10
  • 114
  • 167
Thomas Schar
  • 1,701
  • 1
  • 12
  • 6
  • 13
    "_the protocol<> keyword_": That's really cool! I think this is what is called an _intersection type_ in the type system theory community. I Java you can only have such types for type parameters with multiple bounds. [This paper](http://www.cs.rice.edu/~javaplt/papers/oopsla2008.pdf) suggests introducing them in Java as first class type, with syntax to denote them. – Lii Jun 16 '15 at 06:24
  • 7
    Nice summary. A couple more important features: Swift protocols can also specify associated type requirements—e.g. a collection type has an associated index type, or a comparable type's comparison methods require a parameter of the same type. And in Swift 2.0, protocol extensions can add actual functionality to types that satisfy a protocol's requirements. – rickster Jun 16 '15 at 06:47
  • 3
    @rickster Java 8 too can add implementation to an interface by tagging a method with the `default` [keyword](https://en.wikipedia.org/wiki/List_of_Java_keywords). See the [Oracle Tutorial](http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html). – Basil Bourque Mar 21 '16 at 02:12
  • 5
    The protocol<> keyword has now been removed in favor of the ampersand. So you can write: let c: A & B – elasticrat Mar 15 '18 at 03:54
  • 3
    In Swift, instead of interfaces, the protocol name is used because in Objective C header files (useless duplicates) from C are called interfaces – Alex78191 Apr 29 '18 at 23:21
36

Complementing @Thomas Schar's answer. The Swift protocol magic comes from the extension.

  • Swift protocols can get implementations via the extension (Swift
    2). Java 8 interface can have default implementations, but it cannot be done "retroactively."
  • In Swift, you can "retroactively" add protocol requirements (and
    its implementations if needed) to any class or structure.
  • Swift protocols do not follow the generic (i.e <..>) customization pattern, but a typealias scheme (i.e. Associated Types). Can be confusing at the start, but can avoid
    "angle bracket blindness" in some cases.
  • Swift has an advanced type pattern matching, allowing to be very specific on where and how protocol requirements and extensions get applied. It can be confusing when coming from Java, but it has a lot of power.
  • A swift protocol can be composed for a property/param (i.e. celebrator: protocol)

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).

Yoon5oo
  • 496
  • 5
  • 11
Jeremy Chone
  • 3,079
  • 1
  • 27
  • 28
  • 10
    Also Swift protocols can have optional members, unlike Java interfaces. – eyeApps LLC Dec 27 '16 at 21:53
  • 6
    A minor point that always comes up in Swift is, there's (ridiculously) no abstract functions, so you just go "print you forgot this one!" ... http://stackoverflow.com/a/24111430/294884 – Fattie Feb 24 '17 at 13:37
  • @Fattie. You can use the "required" keyword on a function to specify it requires a subclass implementation. So really, more like a minor ignorance than an actual point. – Dirk Bester Jun 30 '20 at 20:09
  • @DirkBester - cheers - wait, you're talking about with initializers ?? – Fattie Jun 30 '20 at 21:29
  • Again @DirkBester I may have some confusion but one can't use `required` before a function in a protocol, you just get `'required' may only be used on 'init' declarations` ... – Fattie Jun 30 '20 at 21:42
0

Just adding one thing because I've been checking protocols combining:

you can combine protocols at any point with the protocol<> keyword.

This is no longer true. Based on this: https://github.com/apple/swift/blob/master/test/type/protocol_composition.swift

This is correct:

func foo ( var1 : A & B ){}