Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Protocol Extension in Swift
Written by Team Kodeco

A protocol extension allows you to provide default implementations for the methods defined in a protocol. This can be useful when you want to add functionality to multiple types that conform to the same protocol.

Here’s an example of a protocol called Named that has a single requirement, a gettable name property:

protocol Named {
  var name: String { get }
}

We can create a struct and a class that conform to the Named protocol and provide their own implementation of the name property.

struct Person: Named {
  let name: String
}

class Dog: Named {
  let name: String
  init(name: String) {
    self.name = name
  }
}

Now, let’s say we want to add a method to the Named protocol that returns a greeting based on the name. We can do this by defining an extension to the Named protocol and providing a default implementation for the method.

extension Named {
  func sayHello() -> String {
    return "Hello, my name is \(name)."
  }
}

Now, all types that conform to the Named protocol will have access to the sayHello() method.

let john = Person(name: "John")
let spot = Dog(name: "Spot")
print(john.sayHello()) // Prints "Hello, my name is John.
print(spot.sayHello()) // Prints "Hello, my name is Spot.

In this example, the sayHello() method is defined in the protocol extension, but the name property is implemented by the conformers.

Note: If a conformer also provides an implementation of a method defined in a protocol extension, that conformer’s implementation will be used instead of the default implementation. This allows for the conformer to override the default implementation if necessary.

© 2024 Kodeco Inc.