Conditional Conformance with Swift 4.1

Quick walkthrough of another new feature of Swift 4.1

Yogesh Manghnani
Published in
2 min readApr 10, 2018

--

Swift is a pretty good language because of features like protocols, extensions etc. With the latest micro-update Swift 4.1 has brought to us a new protocol feature called conditional conformance. Before we dive in lets build up the learning scenario.

Consider a protocol as below

And consider a structure of a vehicle

Now suppose this we create an array of vehicles. And we want all the vehicles to move. One way to do that is by looping through each element in the array and using the run function on them. Another way to do it is using conditional conformances.

When using conditional conformance what we do is, we extend Arrays by adding the function move() such that the array confirms to Movable protocol given that the Element in the array confirms to the Movable protocol. This can be done as below

With this implemented we can call our move() function on our Array of Vehicles and all the Elements of our Array will start to move.

Follow me on GitHub, Instagram, Facebook, WordPress and Medium.

✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.

--

--

I am fullstack developer who can’t sleep with bugs. (both in bed and in code)