Explanatory examples of protocol benefits vs Java interfaces?

These may be easier to understand if you don't view protocols as types. For example:

protocol Thing { }

var p: Thing

Instead of reading this declaration as “the type of p is Thing”, read it as “p can hold an instance of any type that conforms to Thing”.

In other words, even though you can't instantiate Thing because it's a protocol, there exists at least one type that conforms to it and whose instances you can assign to p.

The confusion arises because the type annotation for the existential “any type that conforms to Thing” is simply Thing. See Improving the UI of generics for a possible solution.

3 Likes