We continue building on the previous topics by introducing the idea of a protocol. I don’t know why, but I kinda like the concept. It’s not something I’ve heard of before but I can see why it could be useful.
In Day 13 we define some properties and functions that it contains and then when you come to create a type that conforms to the protocol
– such as a struct
– Xcode enforces the implementation of those properties and functions. The nice thing is, the implementation can vary per type as long as it contains the minimum functionality defined in the protocol
itself.
We also look at how to extend protocols, and why you’d want to. Overall, a nice feature of the language.
Checkpoint 8
We also have another checkpoint today, this time we need to define our own protocol and then make a couple of different types which conform to it. This one isn’t hard.
protocol Building {
var rooms: Int { get set }
var cost: Int { get set }
var agent: String { get set }
func summary()
}
struct House: Building {
var rooms: Int
var cost: Int
var agent: String
func summary() {
print("This house has \(rooms) rooms, costs £\(cost) and is being sold by \(agent).")
}
}
struct Office: Building {
var rooms: Int
var cost: Int
var agent: String
func summary() {
print("This office has \(rooms) rooms, costs £\(cost) and is being sold by \(agent).")
}
}