Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Protocol Inheritance in Swift
Written by Team Kodeco

In Swift, protocols can inherit from other protocols in a similar way to classes inheriting from superclasses. This allows you to build complex protocols by reusing existing ones.

Here is an example of how to use protocol inheritance:

protocol Shape {
  func draw() -> String
}

protocol Rectangle: Shape {
  var width: Double { get }
  var height: Double { get }
}

struct Square: Rectangle {
  let side: Double
  var width: Double { return side }
  var height: Double { return side }
  func draw() -> String {
    return "I am a square with side of length \(side)
  }
}

In this example, we define a Shape protocol that has a single draw method. We then define a Rectangle protocol that inherits from Shape and adds two properties, width and height. Finally, we define a Square struct that conforms to the Rectangle protocol.

You can use any protocol that inherits from another protocol in the same way as the parent protocol. So in this example, Square struct can be used wherever Rectangle protocol is used.

© 2024 Kodeco Inc.