Menu
Coddy logo textTech

Parking Garage

Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 55 of 57.

challenge icon

Challenge

Hard

Build a parking garage. The protocol Vehicle has plate, size (an enum Size: Int, Comparable with small = 1, medium = 2, large = 3) and hourlyRate. Implement Motorbike (small, 1 per hour), Car (medium, 3) and Van (large, 5). The class Garage is created with a number of spots per size. park(_:) puts a vehicle in a free spot of its own size or, if none is free, of the next larger size, and replies parked AB12 in medium or full for AB12. leave(plate:hours:) frees the spot and replies AB12 paid 9 (rate times hours, at least 1 hour), or no vehicle AB12. status() replies free: small 1, medium 0, large 2.

The supplied code reads the spots as small,medium,large, then commands park car AB12, leave AB12 3 or status, and prints each reply.

Your code goes in Size.swift, Vehicle.swift, Motorbike.swift, Car.swift, Van.swift and Garage.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
let s = input[0].split(separator: ",").map { Int($0)! }
let garage = Garage(small: s[0], medium: s[1], large: s[2])
for cmd in input.dropFirst() {
    let p = cmd.split(separator: " ").map(String.init)
    switch p[0] {
    case "park":
        let v: any Vehicle
        switch p[1] {
        case "bike": v = Motorbike(plate: p[2])
        case "van": v = Van(plate: p[2])
        default: v = Car(plate: p[2])
        }
        print(garage.park(v))
    case "leave": print(garage.leave(plate: p[1], hours: Int(p[2])!))
    default: print(garage.status())
    }
}

All lessons in Object Oriented Programming

Practice on your own: Swift playground