Skip to main content

Checkpoint for protocols and extensions

·282 words·2 mins

Checkpoint for protocols and extensions #

Checkpoint 8

Now that you understand how protocols and extensions work, it’s time to pause our learning and take on a challenge so you can put it all into practice. Your challenge is this: make a protocol that describes a building, adding various properties and methods, then create two structs, House and Office, that conform to it. Your protocol should require the following:

  • A property storing how many rooms it has.
  • A property storing the cost as an integer (e.g. 500,000 for a building costing $500,000.)
  • A property storing the name of the estate agent responsible for selling the building.
  • A method for printing the sales summary of the building, describing what it is along with its other properties.

My implementation that seems to tick the bosses are:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
protocol Building {
    var rooms: Int { get }
    var cost: Int { get }
    var type: String { get }
    var estateAgent: String { get }
    func printSalesSummary()
}
extension Building {
    func printSalesSummary() {
        print("\(type) has \(rooms) rooms and costs \(cost) - sold by \(estateAgent)")
    }
}
struct House: Building {
    let type = "House"
    var rooms: Int
    var cost: Int
    var estateAgent: String
}
struct Office: Building {
    let type = "Office"
    var rooms: Int
    var cost: Int
    var estateAgent: String
}

var house1 = House(rooms: 5, cost: 100000, estateAgent: "John")
var office1 = Office(rooms: 10, cost: 200000, estateAgent: "Jane")

var sellable_buildings: [Building] = [house1, office1]

for building in sellable_buildings {
    building.printSalesSummary()
}