Skip to content

Last modified: May 4, 2025

Protocols

describes an "intent to conform" for disparate types
    similar to an interface in C#/Java
use protocol keyword
    then declare properties and methods, no implementation
    static properties/methods are acceptable
    protocols can also require specific initializers
classes, enums, structs can all adopt protocols
    protocol members that modify a struct must be declared with "mutating"
extend the protocol using inheritance syntax

protocol FullyNamed {
    var fullName : String { get }
}

protocol RandomNumberGenerator {
    func random() -> Double
}
class Dice {
    let sides : Int
    let generator : RandomNumberGenerator
    init(sides: Int, generator: RandomNumberGenerator) {
      self.sides = sides
      self.generator = generator
    }
    func roll() -> Int {
      return Int(generator.random() * Double(sides)) + 1
    }
}
protocol DiceGame {
    var dice : Dice { get }
    func play()
}
protocol DiceGameDelegate {
    func gameDidStart(game: DiceGame)
    func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)
    func gameDidEnd(game: DiceGame)
}