Protocols & Extensions – Swift
Describing behavior, default implementations, and extending existing types.
A protocol describes requirements (properties, methods) that types must fulfill, similar to interfaces. Structs, classes, and enums can adopt protocols. With an extension you give the protocol default implementations (Swift calls this *protocol-oriented programming*).
protocol Tier {
var name: String { get }
func sprich() -> String
}
extension Tier {
func sprich() -> String { "\(name) makes a sound" } // default
}
struct Hund: Tier {
let name: String
func sprich() -> String { "\(name) says Woof!" }
}
struct Katze: Tier {
let name: String
}
let tiere: [any Tier] = [Hund(name: "Rex"), Katze(name: "Tom")]
for t in tiere { print(t.sprich()) }
// Rex says Woof!
// Tom makes a soundany Tier stands for “any type that conforms to Tier” (existential, dynamic call). some Tier, on the other hand, means “one specific but hidden type”: faster and without loss of type information. In parameters and return values, some is often the better choice:
func vorstellen(_ t: some Tier) {
print("Introduced:", t.sprich())
}
vorstellen(Hund(name: "Bello")) // Introduced: Bello says Woof!
func lauteTiere() -> [any Tier] {
[Hund(name: "A"), Katze(name: "B")] // different types: any required
}
print(lauteTiere().count) // 2Extensions add methods and computed properties to any type, even foreign ones, even Int or String. Commonly used standard protocols: Equatable, Hashable, Comparable, Codable, Identifiable, CustomStringConvertible.
extension Int {
var istGerade: Bool { self % 2 == 0 }
func hoch(_ n: Int) -> Int { (0..<n).reduce(1) { acc, _ in acc * self } }
}
print(4.istGerade, 3.hoch(4)) // true 81
struct Version: Comparable, CustomStringConvertible {
let major: Int
let minor: Int
static func < (l: Version, r: Version) -> Bool {
(l.major, l.minor) < (r.major, r.minor)
}
var description: String { "\(major).\(minor)" }
}
let versionen = [Version(major: 1, minor: 5), Version(major: 1, minor: 2)]
print(versionen.sorted(), versionen.max()!) // [1.2, 1.5] 1.5Codable & Identifiable) and restricted to conditions: extension Array where Element: Numeric { ... }. For structs you often get Equatable, Hashable, and Codable automatically; you just write : Equatable.any Tier value calls the default implementation even if the concrete type has its own method of the same name. Whatever should be overridable belongs in the protocol.