Interfaces and protocols
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
- Requirements: methods, properties (
{ get }/{ get set }), initializers,associatedtype, static members. - Default implementations in an
extension: a conformer may omit them. So "you must implement every method" is wrong for Swift. - Protocol inheritance and composition:
any Codable & Sendable. - Conditional conformance:
extension Array: Drawable where Element: Drawable. - Class-only protocols:
protocol P: AnyObject, needed forweakdelegates.
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
any Pis an existential container: the type is erased, calls go through the witness table, heap boxing is possible. Needed for heterogeneous collections and storing "some value of P".some Pis an opaque type: exactly one concrete type, known to the compiler, static dispatch. Preferred in function signatures.
What the interviewer looks for
- A protocol is the tool for testability (replacing dependencies with stubs) and decoupling modules.
- Protocol-oriented programming: behaviour is added through protocol
extensions rather than a base class. - Trap: extension methods that are not declared as protocol requirements are dispatched statically.