Recap: Booking Ledger
Lesson 42 of 48 in Coddy's Swift for Python Developers course.
Challenge
EasyImplement reference type BookingLedger(capacity:) with read-only used initially zero and reserve(_ count: Int) -> Bool. Accept only positive counts fitting remaining capacity, update used once, and return true. Rejection preserves state. Input is capacity 0 through 100 then 0 through 30 requests -10 through 100. Output used and accepted request count separated by a space.
Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.
Your code goes in BookingLedger.swift, Functions.swift. main.swift holds the supplied input/output code and cannot be edited.
Try it yourself
import Foundation
func apiChecks(_ input: String) -> Bool {
let x = BookingLedger(capacity: 9); guard x.reserve(4) && !x.reserve(6) && !x.reserve(0) && x.used == 4 else { return false }; return x.reserve(5) && x.used == 9 && !x.reserve(1)
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
All lessons in Swift for Python Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry Rules5Collection Tools
Dictionaries and Missing KeysSets and MembershipUnicode and Character IndicesClosures and TransformationsRecap: Catalog Merge8Designing Types
Inheritance and OverridesComposition Through a PolicyAccess Control and InvariantsEnums with Associated ValuesFailable InitializationRecap: Booking LedgerPractice on your own: Swift playground