Instruction

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

So what is a protocol? Here’s the official Swift definition:

A protocol defines a blueprint of methods, properties and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.

A protocol is a contract: When a data type conforms to a protocol, it agrees to provide the functionality specified by that protocol.

Swift’s Standard Library Protocols: Ready-Made Tools for Your Code

Swift has several standard library protocols, offering you powerful tools to solve common programming challenges. Now, you’ll explore two essential ones:

  • Equatable: This protocol allows you to determine whether two instances of a data type are equal. If all of a struct’s stored properties are types that conform to Equatable — like Int, String, Bool etc. — then you only need to add : Equatable after its name. For a class, you must define static func ==(lhs:rhs:) to specify how to compare two instances.

Try out an example by extending the MuseumObject class to conform to the Equatable protocol in Swift.

extension MuseumObject: Equatable {
  static func ==(lhs: MuseumObject, rhs: MuseumObject) -> Bool {
    // return the condition that determines equality of two instances
  }
}

Note: It’s common to define a protocol’s required methods and computed properties in an extension. Xcode helps you out by offering to add protocol stubs.

You’ll explore this further in the demo portion of this lesson.

  • CustomStringConvertible: Sometimes, you want instances of your type to provide human-readable descriptions of themselves. An instance can convert itself into a descriptive String. To conform to this protocol, a struct or class must define a description property. Here’s an example:
extension MuseumObject: CustomStringConvertible {
  var description: String {
    // return human-reader-friendly string
  }
}

In the demo, you’ll learn more about how this enhances your code’s readability.

Defining Your Own Protocols: Tailoring Your Interfaces

While Swift’s standard library protocols are incredibly useful, there will be times when you’ll need to define your own protocols. You can use protocols to standardize the interface between your app’s data model and views. Here’s why and how:

protocol ImageDataProvider {
  var image: UIImage? { get }
}

extension TiltShiftOperation: ImageDataProvider {
  var image: UIImage? { outputImage }
}
protocol CanFly {
  var speed: Double
  func fly(direction: Double)
}
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo