Generic Protocols in Swift

Arvindh Sukumar
Dispatch Swift
Published in
2 min readApr 14, 2016

--

A protocol in Swift is generic when it does not enforce types in (some or all of) its variables and functions, on types that conform to it. Different conforming types can then implement the protocol in ways that’re relevant or convenient for them.

There are two ways to make a protocol generic:

  1. By adding a Self Requirement
  2. By using Associated Types

Protocols with Self requirement

The type for function parameters can be marked as Self. When this is done, the type is automatically resolved to the type of the conforming object. For example:

Protocols with self won’t work in the following cases though:

  • Properties of type Self aren’t allowed. (I’m unable to find any documentation for this though — this just doesn't compile, when I tried. But when you think of it, the use-case for this is pretty limited — how often do you have one type owning an instance of the same type?)
  • if Self is the return type of a function. For example:

Associated Types

When using Self, there is only one generic type possible — the conforming type itself. Instead, it’s also possible to declare one or more associatedtypes inside the protocol. An associated type is a type that can be filled in later by the conforming type. Inside the protocol, it is just a declaration — It is upto the conforming type to define what that associatedtype is.

In the above example, the associatedtype can be instances of a String, an Enum, or an array of Strings! The best part is that it’s upto the conforming type to provide this implementation detail — and it can choose the one that’s the most appropriate.

Conclusion

Generic protocols offer a lot of flexibility in enabling similar functionality across varied types. In this age of Protocol-oriented Programming, they’re definitely wonderful tools to have in your toolbox.

--

--