Protocol Extension

Introduction

Welcome to Lesson 2 of Protocol Oriented Swift. You will learn a magic. You will dramatically reduce the number of lines of code.

Problem

I don’t even want to type anymore.

Create Protocol

Create a protocol called MathGenius that contains one method.

  1. protocol MathGenius {
  2. func calculateGPA()
  3. }

Create Protocol Extension

Create an extension to MathGenius. The extension contains a default method.

  1. extension MathGenius {
  2. func calculateGPA() {
  3. print("I'm too cool for skool")
  4. }
  5. }

Create a struct that conforms to MathGenius. Since the extension provides a default method, you no longer have to specify the required method. If you do, it will override the default method.

  1. struct Bob: MathGenius {
  2. func calculateGPA() {
  3. print("1.2 GPA")
  4. }
  5. }
  6. Bob().calculateGPA() // "1.2 GPA""

You don’t have to provide the default method due to extension.

  1. struct Bobby: MathGenius {}
  2. Bobby().calculateGPA() // "I'm too cool for skool"

Practical Protocol Extension

Create a protocol that contains a method that takes two Double parameters and returns String.

  1. protocol FindAreable {
  2. func calculateArea(side: Double, length: Double) -> String
  3. }

Create an extension to FindAreable which will return a statement whose type is in String.

  1. extension FindAreable {
  2. func calculateArea(side: Double, length: Double) -> String {
  3. let area = String(side * length)
  4. return "The area is \(area)"
  5. }
  6. }

Every struct and class that conforms to FindArea contains the default calculateArea method from the extension.

  1. struct Square: FindAreable {}
  2. struct Hexagon: FindAreable {}
  3. Square().calculateArea(side: 4, length: 4)
  4. Hexagon.init().calculateArea(side: 6, length: 10)

Usage Case

  • UILabel, UIImageView, UIView —> Animation
  • Storyboard Identifier
  • Reusable table and collection view cells

Resources

If you are interested in how you may apply Protocols to UIKit, you may read Protocol Oriented View with Bob (Blog).

Source Code

4002_protocol_extension.playground

Conclusion

Protocol Oriented Swift is only limited by your imagination.

Note: Learn Swift with Bob is available on Udemy. If you wish to receive a discount link, you may sign up here.