Recap - Library Card
Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 6 of 57.
Challenge
MediumComplete the class LibraryCard. Its initializer takes the member name and a limit (default 3) and starts with no borrowed books. borrow(_:) returns true and adds the title unless the card is at its limit or already holds that title. giveBack(_:) returns true when it removed the title. status() returns Ada: 2/3 (Dune, Emma) with the titles in borrowing order, or Ada: 0/3 when nothing is borrowed.
The supplied code reads the name, the limit (or an empty line for the default) and then commands +title or -title. It prints ok or no for each command and finally status().
Your code goes in LibraryCard.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 card = input[1].isEmpty ? LibraryCard(name: input[0]) : LibraryCard(name: input[0], limit: Int(input[1])!)
for cmd in input.dropFirst(2) {
let title = String(cmd.dropFirst())
let done = cmd.hasPrefix("+") ? card.borrow(title) : card.giveBack(title)
print(done ? "ok" : "no")
}
print(card.status())
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