Protocols & Extensions

Yesterday I worked through the protocols & extensions section of 100 Days of Swift. I stayed up a little late to finish reading a new book, so today I’m catching up on my writing.

I discovered a few things yesterday only via the tests, which was kinda neat. For example, I didn’t know that a variable with a setter must also have a getter, or that variables in protocols must have { get } or { get set } specifiers.

One thing that was new to me was protocol inheritance:


protocol Westerner {
    var name: String { get set }
    var town: String { get set }
}

protocol Dueler {
    func duel(_ other: Dueler)
}

protocol Cowboy: Westerner {
    func wrangleHorses()
    func driveCattle()
    func rodeo()
}

protocol Farmer: Westerner {
    func plantCrop(_ crop: String)
    func carryWater()
}

protocol Outlaw: Westerner, Dueler {
    func rob(_other: Westerner)
}

protocol Sheriff: Westerner, Dueler {
    func arrest(_ other: Westerner)
}

I am also a little confused about getter property syntax. These two are both read-only properties, the get { } part is optional if there is no setter:

extension Dueler {
    var pistol: String {
        return "Colt 45"
    }
    
    var rifle: String {
        get {
            return "Winchester Model 1873"
        }
    }
}