The power of Generics and Protocol Conformance in Swift.

Lehlohonolo Isaac
Obj-Swift-Mzanzi
Published in
2 min readMay 30, 2018

--

Photo by Albert S on Unsplash

In Swift Protocols and Generics work along and hand-in-hand very well. There’s actually a term used to simplify this relationship. It’s called DRY (Don’t Repeat Yourself), which simply means: Use Abstractions to avoid duplication. Thus, here I’ll demonstrate to you how powerful Generics are in Swift as well as how protocol conformance can boost Generics.

Let’s take a look at these examples:

Say you want to determine if two things are equal. Writing a function that returns a boolean to return true/false based on whether the two things we are comparing are equal or not. For example, let’s write a function to test if two integer values are equal or not:

function to test if two integers are equal.

Cool, now this will test if two integers are equal. However, it won’t be able to test for other types such as Double’s, Floats, and other Swift types that can be equatable. Thus, using Generics in Swift as well as protocol conformance, we can do this:

Using generics to rewrite the equal function.

Oh-oh, what’s happening now? Why is there an error?

The error is due to the fact that T is a generic type and it’s not known whether it can be equatable or not. This is where protocol conformance comes to play an important role; whereby we force the equal function to only take as parameters types that are equatable. This is how we can do that in Swift:

Making the generic T to be an Equatable type.

Or,

Making the generic T be an Equatable type.

As you have seen from the above code snippets how generics and protocol conformance can really help you to avoid writing duplicate code. It’s a good practice if you start playing around with generics and protocols more frequently in your codebase. It’ll surely simplify your life as a developer.

--

--