0Pricing
Swift Academy · Lesson

Protocols as Contracts

Define behavior contracts independent of types.

What Is a Protocol?

A protocol defines a blueprint of methods, properties, and other requirements that a conforming type must implement. It is a contract: any type that adopts it promises to provide everything the protocol declares.

protocol Greetable {
    var name: String { get }
    func greet() -> String
}

Conforming to a Protocol

A type conforms by adopting the protocol and supplying every requirement. Here a struct fulfills both the name property and the greet() method.

protocol Greetable {
    var name: String { get }
    func greet() -> String
}

struct Person: Greetable {
    let name: String
    func greet() -> String { "Hello, I am " + name }
}

let p = Person(name: "Ada")
print(p.greet())

All lessons in this course

  1. Protocols as Contracts
  2. Default Implementations in Extensions
  3. Protocol Composition
  4. Conditional Conformance
← Back to Swift Academy