Learning w/ Swift

Understanding Protocols in Swift

Protocols in Swift allow us to create blueprints for how classes, structs and enums should work.

They allow us to define exactly what properties and functions data types that conform to our protocol must contain to be valid. Types that conform to protocols can contain more than what is required, but must at least contain the bare minimum as defined in the protocol.

They are useful for minimizing the amount of otherwise duplicate code within our data types, and guaranteeing that otherwise unrelated types play nicely together.

protocol Purchaseable {
    var name: String { get set }
}

struct Car: Purchaseable {
    var name: String
    var manufacturer: String
}

struct Coffee: Purchaseable {
    var name: String
    var strength: Int
}

func buy(_ item: Purchaseable) {
    print("I'm buying \(item.name)")
}