CodeToLive

Protocols & Extensions in Swift

Protocols define blueprints of methods, properties, and other requirements for conforming types.

Protocol Definition

protocol Vehicle {
    var speed: Double { get set }
    func accelerate()
    func brake()
}

Protocol Conformance

struct Car: Vehicle {
    var speed = 0.0
    
    func accelerate() {
        speed += 10
    }
    
    func brake() {
        speed = max(0, speed - 10)
    }
}

Protocol Inheritance

protocol ElectricVehicle: Vehicle {
    var batteryLevel: Double { get }
    func charge()
}

Extensions

extension Int {
    func squared() -> Int {
        return self * self
    }
}

print(5.squared())  // 25

Protocol Extensions

extension Collection {
    func summarize() {
        print("Collection has \(count) items")
    }
}

[1, 2, 3].summarize()

Common Protocols

Protocol Purpose
Equatable For values that can be compared for equality
Comparable For values that can be compared with <, >, etc.
Codable For types that can be encoded/decoded
← Back to Tutorials