Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as ngcohhlev text.

Heads up... You’re accessing parts of this content for free, with some sections shown as ltqelqlum text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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:

Heads up... You’re accessing parts of this content for free, with some sections shown as mcgotwjix text.

Heads up... You’re accessing parts of this content for free, with some sections shown as jkbakxmor text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now
extension MuseumObject: Equatable {
  static func ==(lhs: MuseumObject, rhs: MuseumObject) -> Bool {
    // return the condition that determines equality of two instances
  }
}
extension MuseumObject: CustomStringConvertible {
  var description: String {
    // return human-reader-friendly string
  }
}

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)
}

Heads up... You’re accessing parts of this content for free, with some sections shown as mpxisvcux text.

Heads up... You’re accessing parts of this content for free, with some sections shown as ghbicmzif text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo