Menu
Coddy logo textTech

Recap - Employee Hierarchy

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

challenge icon

Challenge

Hard

Build a staff directory. Person stores name and has role() returning person and card() returning Ada (person), built from role(). Staff: Person adds department, set in its own initializer before super.init, and overrides role() to return staff in <department>. Manager: Staff adds team (an array of Staff, empty at first), a method hire(_:), and overrides role() to return the Staff role followed by , 2 reports. Contractor: Person is final, adds days, and overrides role() to return contractor for 30 days.

The supplied code reads lines staff,name,dept, manager,name,dept, contractor,name,days and hire,manager,staff (the manager hires a staff member by name). It prints card() for every person in the order they were created.

Your code goes in Person.swift, Staff.swift, Manager.swift and Contractor.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) }
var people: [Person] = []
for line in input {
    let p = line.split(separator: ",").map(String.init)
    switch p[0] {
    case "staff": people.append(Staff(name: p[1], department: p[2]))
    case "manager": people.append(Manager(name: p[1], department: p[2]))
    case "contractor": people.append(Contractor(name: p[1], days: Int(p[2])!))
    default:
        let boss = people.first { $0.name == p[1] } as? Manager
        let member = people.first { $0.name == p[2] } as? Staff
        if let boss = boss, let member = member { boss.hire(member) }
    }
}
for person in people { print(person.card()) }

All lessons in Object Oriented Programming

Practice on your own: Swift playground