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
REPORTThe 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:
falsehandle(_:) 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 HobbitChallenge
EasyComplete Library.handle(_:) for the first two commands:
ADD_BOOK <id> <title>: store a new available book and replyadded book 1: Dune; when the id is taken replybook 1 exists.JOIN <name>: add a member and replywelcome ada; when the name exists replyada 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) }
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesMethods and selfInitializersClasses Are ReferencesRecap - Library Card4Encapsulation
Access ControlRead-Only From OutsideGuarding StateFailable InitializersRecap - Bank Account7Polymorphism and Generics
PolymorphismType CastingGeneric FunctionsGeneric TypesRecap - Shape Calculator5Inheritance
SubclassesOverriding MethodsInitializers and superfinal and HierarchiesRecap - Employee Hierarchy11Project: Library Management
Books and MembersBorrowing BooksPractice on your own: Swift playground