Start learning free

LESSON 648 OF 678 · OBJECT-ORIENTED PROGRAMMING

Interfaces in Swift

Lesson

TL ; DR:

An interface (a protocol in Swift) is a pure contract — a list of methods that a class promises to implement, with no shared data and no shared code. Unlike inheritance ("is a"), interfaces express "can do".


protocol Speaker {
    func speak()
}
class Dog: Speaker {
    func speak() {
        print("Woof")
    }
}


Full lesson:

An interface defines what a class can do, not how it does it or what it is. A Truck, a Robot, and a Drone aren't the same kind of thing — but they can all move(). You'd put move() in a Movable protocol and have each one adopt it.

Interface vs abstract class

Abstract classInterface
Has fieldsYesNo stored fields (a protocol can only require properties)
Has method bodiesYes (some)No (default implementations only through a protocol extension)
Multiple "inheritance"Usually noYes — a class can adopt many protocols
Models"is a""can do"

A class inherits from at most one parent class but can adopt many protocols. That's why protocols are the right tool for cross-cutting capabilities like Comparable, Equatable, Codable, Sequence, etc.

The language landscape

  • Swift — the keyword is protocol. A class lists the protocols it adopts after its name (and after its superclass, if it has one), separated by commas; structs and enums can adopt protocols too.
  • C# / Java — first-class interface keyword. C# uses : for both inheritance and implementation; Java uses extends for inheritance and implements for interfaces.
  • Python — no separate interface; abstract base classes (ABCs) with all-abstract methods serve the same role.
  • JavaScript — no interface keyword in plain JS (TypeScript has it). The convention is a stub class.
  • C++ — a class with only pure-virtual methods is an interface. Multiple inheritance lets a class implement several.

Your task

The Speaker protocol is already declared. Create a Dog class that adopts it, with a speak() method that prints "Woof".

Expected output:

Woof
STEP 1 OF 2
    Ctrl + Enter to check