Menu
Coddy logo textTech

Books and Members

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

In this project you build the core of a library system. A Library class receives commands, one per line, and replies to each. Over five steps it learns to add books and members, lend and take back books, search the catalogue and print a report.

ADD_BOOK 1 Dune
JOIN ada
BORROW ada 1
RETURN ada 1
SEARCH dune
REPORT

The data model uses the tools of this section. Book is a struct: a value whose borrower changes. Member is a class, because the library and a member's list of loans refer to the same person. The library keeps both in private dictionaries, so only its methods can change them:

struct Book {
    let id: Int
    let title: String
    var borrower: String? = nil
    var isAvailable: Bool { borrower == nil }
}

var books: [Int: Book] = [:]
books[1] = Book(id: 1, title: "Dune")
books[1]!.borrower = "ada"
print(books[1]!.isAvailable)

Output:

false

handle(_:) splits the command and switches on its first word. Every branch returns its replies as an array, so a command such as REPORT can reply with several lines. The title of a book can contain spaces, so it is everything after the id:

let p = "ADD_BOOK 7 The Hobbit".split(separator: " ").map(String.init)
let id = Int(p[1])!
let title = p.dropFirst(2).joined(separator: " ")
print("\(id): \(title)")

Output:

7: The Hobbit
challenge icon

Challenge

Easy

Complete Library.handle(_:) for the first two commands:

  • ADD_BOOK <id> <title>: store a new available book and reply added book 1: Dune; when the id is taken reply book 1 exists.
  • JOIN <name>: add a member and reply welcome ada; when the name exists reply ada is already a member.

The supplied code passes every input line to library.handle(_:) and prints each returned reply on its own line. Member names are single lower-case words, book ids are whole numbers, and the input holds only the commands described so far. Any other command replies unknown command.

Your code goes in Book.swift, Member.swift and Library.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 library = Library()
for line in input {
    for reply in library.handle(line) { print(reply) }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Swift playground