0Pricing
Swift Academy · Lesson

Protocols as Contracts

Define behavior contracts independent of types.

Protocols as Contracts is a free Swift Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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())

Property Requirements

Protocols specify whether a property must be gettable ({ get }) or both gettable and settable ({ get set }). A stored or computed property can satisfy a get-only requirement.

protocol Identifiable {
    var id: String { get }
}

struct User: Identifiable {
    let id: String
}

print(User(id: "u-1").id)

Method Requirements

Method requirements list the name, parameters, and return type but no body. Conforming types provide the implementation.

protocol Shape {
    func area() -> Double
}

struct Square: Shape {
    let side: Double
    func area() -> Double { side * side }
}

print(Square(side: 3).area())

mutating Requirements

For value types, methods that change self must be marked mutating. Declare the requirement with mutating so structs can satisfy it.

protocol Toggleable {
    mutating func toggle()
}

struct Switch: Toggleable {
    var isOn = false
    mutating func toggle() { isOn.toggle() }
}

var s = Switch()
s.toggle()
print(s.isOn)

Protocols as Types

A protocol is a first-class type. You can use it for variables, parameters, and return values, accepting any conforming value.

protocol Animal { func sound() -> String }
struct Dog: Animal { func sound() -> String { "Woof" } }
struct Cat: Animal { func sound() -> String { "Meow" } }

let animals: [Animal] = [Dog(), Cat()]
for a in animals { print(a.sound()) }

Polymorphism via Protocols

Calling a protocol method dispatches to the concrete type behind the value. This lets you write code that works across many types through one contract.

protocol Describable { func describe() -> String }
struct Book: Describable { let t: String; func describe() -> String { "Book: " + t } }
struct Film: Describable { let t: String; func describe() -> String { "Film: " + t } }

func show(_ d: Describable) { print(d.describe()) }
show(Book(t: "Swift"))
show(Film(t: "Inception"))

Initializer Requirements

Protocols can require initializers. Classes must mark the implementation required so subclasses also provide it.

protocol FromInt {
    init(value: Int)
}

struct Wrapper: FromInt {
    let value: Int
    init(value: Int) { self.value = value }
}

print(Wrapper(value: 42).value)

Protocol Inheritance

A protocol can inherit from one or more other protocols, adding extra requirements on top of the inherited ones.

protocol Named { var name: String { get } }
protocol Aged: Named { var age: Int { get } }

struct Member: Aged {
    let name: String
    let age: Int
}

let m = Member(name: "Lin", age: 30)
print(m.name, m.age)

Class-Only Protocols

Mark a protocol with AnyObject to restrict conformance to classes, which is useful for reference-semantic requirements like delegation.

protocol Counter: AnyObject {
    var count: Int { get set }
}

class Box: Counter {
    var count = 0
}

let b = Box()
b.count = 5
print(b.count)

Checking Conformance

Use is and as? to test whether a value conforms to a protocol at runtime.

protocol Flyer { func fly() }
struct Bird: Flyer { func fly() { print("flap") } }
struct Rock {}

let things: [Any] = [Bird(), Rock()]
for t in things {
    if let f = t as? Flyer { f.fly() } else { print("grounded") }
}

Quick Check

Test your understanding of protocol requirements.

Recap

You learned that a protocol is a contract: it declares property, method, mutating, and initializer requirements without implementations. Types conform by satisfying every requirement, protocols can be used as types for polymorphism, can inherit from other protocols, and can be restricted to classes with AnyObject.

Frequently asked questions

Is the “Protocols as Contracts” lesson free?

Yes — the full text of “Protocols as Contracts” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Protocols as Contracts”?

Define behavior contracts independent of types. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Protocols as Contracts” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

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