Protocols - RaduG/swift_learning GitHub Wiki

Overview

Equivalents to interfaces in other languages. The list of protocols a class implements must be listed after its superclass.

protocol MyProtocol {}
class MyClass: BaseClass, MyProtocol {}
protocol TextRepresentable {
  var textDescription: String { get }
}

extension Dictionary: TextRepresentable where Key: TextRepresentable {
  var textDescription: String {
    var desc = ""

    for (key, value) in self {
      desc += "\(key.textDescription): \(value)\n"
    }

    return desc
  }
}
 
struct SomeStruct: TextRepresentable, Hashable {
  let value: Double
  var textDescription: String {
    "Hello! My value is \(value)"
  }
 
  init(_ value: Double) {
    self.value = value
  }

}


extension Int: TextRepresentable {
  var textDescription: String {
    "I am an Int and my value is \(self)"
  }
}


struct SomeOtherStruct: Hashable {
  let value: Double

  var textDescription: String {
    "As a struct, my value is \(value)"
  }
}

extension SomeOtherStruct: TextRepresentable {}  // conformance after declaration


var myDict: [TextRepresentable: Double] = [SomeStruct(12): 12, SomeStruct(13.5): 17]
print(myDict.textDescription)

Class-only protocols

protocol ClassOnlyProtocol: AnyObject {}

Protocol composition

& can be used to compose protocols

func myFunc(x: SomeProtocol & SomeOtherProtocol) {}

x must conform to both SomeProtocol and SomeOtherProtocol.

Protocol extensions

Protocols can be extended to actually provide implementations:

extension RandomNumberGenerator {
  func randomBool() -> Bool {
    return random() > 0.5
  }
}