Protocol comparison in Swift vs Interface in Java

I am learning an iOS tutorial from the Apple Developers page .

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

  • Are there any differences between the two?

  • using difference in a project?

Updated

Yes I read the link above and I'm still not sure what the differences and usage are between protocol and interface . When I ask such a question, I would like a simple explanation of this topic. Sometimes it can be difficult to get everything from the documentation.

+71
java swift
Jun 16 '15 at 5:17
source share
2 answers

In essence, the protocols are very similar to Java interfaces, with the exception of:

  • Swift protocols can also indicate properties that should be implemented (e.g. fields)
  • Swift protocols must handle the value / reference using the mutating keyword (since protocols can be implemented using structures and classes)
  • You can combine protocols anywhere with the keyword. For example, declaring a function parameter that should adhere to protocols A and B as:

.

 func foo ( var1 : protocol<A, B> ){} 

These are immediately obvious differences for the Java developer (or at least what I have noticed so far).

+52
Jun 16 '15 at 6:00
source share
— -

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

  • Swift protocols can receive implementations through the extension (Swift | 2). The Java 8 interface may have standard implementations, but it cannot be done retroactively.
  • In fast mode, you can "retroactively" add protocol requirements (and its implementation if necessary) for any class or structure.
  • Swift protocols do not match the generic type configuration template (ie <...>), but the type scheme (for example, related types). It can be confusing at startup, but can be avoided in some cases - “blindness of the angle bracket”.
  • Swift has an extended type pattern mapping, which allows a specific question about where and how the requirements and protocol extensions apply. It can be confusing when it comes to Java, but it has a lot of power.
  • The Swift protocol can be configured for the / param property (i.e. celebrator: Protocol)

One thing that made me scratch my head for several hours was that not all protocols can be used as a type of property. For example, if you have a protocol with typealias, you cannot directly use it as a type of property (this makes sense if you think about it, but from Java, we really want to have a property like userDao: IDao).

+18
Jun 29 '15 at 17:35
source share



All Articles