zzz6519003 / blog

My blog about coding
4 stars 1 forks source link

Protocol-Oriented Programming Tutorial in Swift - Extending Protocols With Default Implementations #147

Open zzz6519003 opened 3 years ago

zzz6519003 commented 3 years ago

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

protocol Flyable {
  var airspeedVelocity: Double { get }
}

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

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

struct Penguin: Bird {
  let name: String
  let canFly = false
}

struct SwiftBird: Bird, Flyable {
  var name: String { "Swift \(version)" }
  let canFly = true
  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
  }
}

insert the following just below the Bird protocol definition:

extension Bird {
  // Flyable birds can fly!
  var canFly: Bool { self is Flyable }
}

Now delete the let canFly = ... from FlappyBird, Penguin and SwiftBird.

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

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

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
  }