DevPrep

All topics › Object-oriented programming (OOP)

Interfaces and protocols

Junior

Essence

An interface (a protocol in Swift and Objective-C) is a contract: a set of requirements a type must satisfy. A type adopting the protocol can be used wherever that protocol is expected, which is the basis of polymorphism without inheritance. In Swift protocols are adopted not only by classes but also by struct, enum and actor.

What Swift protocols can do

import Foundation

protocol Identifiable2 {
    associatedtype ID: Hashable
    var id: ID { get }            // property requirement
}

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

extension Greeter {
    // default implementation: conformers may omit it
    func greet() -> String { "Hello, \(name)" }
}

struct User: Greeter, Identifiable2 {
    let id: UUID = UUID()
    let name: String
}

let anyGreeter: any Greeter = User(name: "Ann")   // existential box
func show(_ g: some Greeter) { print(g.greet()) } // generic, static dispatch
show(User(name: "Bob"))      // Hello, Bob
print(anyGreeter.greet())    // Hello, Ann

any vs some

What the interviewer looks for

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store