INTRODUCTION TO POP

INTRODUCTION TO POP

Khoshimov Shavkatbek

Swift is a protocol-oriented programming language

“Don’t start with a class, Start with a protocol”.
  • An advantage of protocols in Swift is that objects can conform to multiple protocols.
  • When writing an app this way, your code becomes more modular. Think of protocols as building blocks of functionality. When you add new functionality by conforming an object to a protocol, you don’t build a whole new object.
  • Protocols allow you to group similar methods, functions, and properties. Swift lets you specify these interface guarantees on classstruct and enum types. Only class types can use base classes and inheritance.

This code defines a simple protocol, Bird with properties name and canFly. It then defines a protocol called Flyable which has the property airspeedVelocity.

protocol Bird {
  var name: String { get }
  var canFly: Bool { get }
}

// Protocol extensions allow you to define a protocol’s default behavior.
extension Bird {
  // only Flyable birds can fly!
  var canFly: Bool { self is Flyable }
}

protocol Flyable {
  var airspeedVelocity: Double { get }
}

In the pre-protocol days of yore, developers would start with Flyable as a base class and then rely on object inheritance to define Bird and any other things that fly.

But in protocol-oriented programming, everything starts as a protocol. This technique allows you to encapsulate the functional concept without needing a base class.

As you’re about to see, this makes the entire system much more flexible when defining types.

struct FlappyBird: Bird, Flyable {
  let name: String
  let flappyAmplitude: Double
  let flappyFrequency: Double

  var airspeedVelocity: Double {
    3 * flappyFrequency * flappyAmplitude
  }
}

It defines a new struct named FlappyBird that conforms to both the Bird and Flyable protocols.


struct Penguin: Bird {
  let name: String
}

struct SwiftBird: Bird, Flyable {
  var name: String { "Swift \\(version)" }
  let version: Double
  private var speedFactor = 1000.0

  init(version: Double) {
    self.version = version
  }

  // Swift is FASTER with each version!
  var airspeedVelocity: Double {
    version * speedFactor
  }
}

Penguin is a Bird, but it cannot fly. Good thing you didn’t take the inheritance approach and make all birds Flyable!

Using protocols, you can define functional components and have any relevant object conform to them.


Report Page