Skip to content
Tutorials Center
My learning

Topics

Lesson 140 of 146 ยท Projects

Project: Appointment Scheduler

Build a doctor appointment scheduler in Swift with Date and Calendar, overlap detection, typed booking errors, free-slot search and Codable JSON saving. A full program that runs in your browser.

Booking systems look simple until two people want the same hour. A doctor's office, a hair salon, a meeting-room calendar and a repair shop all solve the same problem: a set of resources (doctors), a set of time slots, and a rule that no two bookings may overlap. The interesting work is in the details: what counts as an overlap, what happens at closing time, what error the user should see, and how to save the whole thing and load it again tomorrow.

In this project you build a small appointment scheduler as a value-type model with a few rules, using Date and Calendar for the time arithmetic, typed errors for everything that can go wrong, and Codable for saving. You will practice dates and calendars, structs, typed throws and Codable. If one of those feels shaky, read it first.

The plan

The pieces, from the bottom up:

TEXT
TimeSlot       a start Date and a length in minutes; knows if it overlaps another
Doctor         an id, a name and working hours
Appointment    who is booked, with which doctor, in which slot
BookingError   every reason a booking can be refused
Schedule       the doctors and appointments, with book / cancel / free slots

Three design decisions are worth stating up front.

  1. Half-open intervals. A 30-minute slot starting at 9:00 occupies 9:00 up to, but not including, 9:30. That way a booking from 9:30 to 10:00 touches it without overlapping, and back-to-back appointments are legal.
  2. Time zones are explicit. The examples pin a Calendar to UTC so you see the same output on every computer. A real app would use the doctor's local time zone and store dates as instants (a Date is always an instant, never "9 o'clock").
  3. "Now" is a parameter. book receives the current time instead of calling Date() inside. The program is then deterministic, and a test can ask what would have happened last Tuesday.

Step 1: slots and overlap

A slot is a start and a length. The end is computed with Calendar, never by adding seconds yourself, so that daylight-saving changes cannot shift it. Two half-open intervals [a, b) and [c, d) overlap exactly when a < d and c < b. Draw two bars on paper if you want to convince yourself.

Swift Step 1: TimeSlot and overlap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The slots a (9:00-9:30) and b (9:30-10:00) do not overlap, because a.end equals b.start and the test uses <. The slot c (9:15-9:45) overlaps both. March 4, 2030 is a Monday, and weekday 2 is Monday in the Gregorian calendar (Sunday is 1).

Step 2: booking with rules

Now add the doctor, the appointment, and a Schedule with a book method. A booking is refused for five different reasons, so an enum with an associated value for each is the natural way to report them (custom errors). book uses typed throws (throws(BookingError)), so the caller knows the complete set of failures. Its checks run from the cheapest to the most expensive: does the doctor exist, is the time in the future, is it inside working hours, and finally does it clash with an existing appointment.

The working-hours check builds the opening and closing instants for the day of the slot. calendar.startOfDay(for:) gives midnight, and byAdding: .hour moves to the opening time.

Swift Step 2: the Schedule and its rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Read the output against the calls. Ben at 9:15 clashes with Ana (and the error carries the clashing appointment, so the message can name her). Ben at 9:30 is fine, because the slots only touch. Cy at 8:30 is before opening, and Cy at 11:45 for 30 minutes would end at 12:15, after closing. Appointment numbers stay in sequence for successful bookings only, because failed calls never reach nextID += 1.

The helper attempt takes a closure that throws any error and prints it with \(error). That is a convenience for the demo. In your own code, prefer to catch the typed error and switch over its cases to decide what to tell the user.

Step 3: cancelling, free slots, saving and loading

Three features finish the program.

  • cancel(_:) removes an appointment by id, and throws noSuchAppointment for an id that does not exist (so cancelling twice reports the second attempt).
  • freeSlots(doctor:on:minutes:) walks from opening to closing in steps of the requested length and keeps every candidate that does not overlap an existing appointment. It reuses overlaps, which is why the interval rule is worth getting right once.
  • Saving needs nothing but Codable. All the model types conform, so JSONEncoder can write the whole Schedule. Set dateEncodingStrategy = .iso8601 so dates are readable and portable (2030-03-04T09:30:00Z), and use the same strategy when decoding. The decoded schedule keeps its private nextID, so numbering continues where it stopped.
Swift Step 3: the complete scheduler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Look at the middle of the output. After the first 45-minute search, the free slots are 10:30 and 11:15, because Ana and Ben occupy 9:00 to 10:00 and a 45-minute candidate at 9:45 would run into Ben. After cancelling Ana's appointment (#1), a 60-minute search offers 10:00 and 11:00 but not 9:00, because Ben (#2) still holds 9:30 to 10:00. The second cancel prints no appointment #1. After saving and loading, Eli's new booking is numbered #4: the counter survived the round trip.

JSON has no date type, which is why the strategy matters. Without one, Date encodes as a number of seconds since 1 January 2001, which most other systems do not expect. ISO 8601 text works with every language. Note also that a dictionary with Int keys, like doctors, is encoded by Codable as a flat array of alternating keys and values, not as a JSON object; use String keys when other programs need to read the file.

Ideas for extending it

  • Add recurring appointments ("every Monday at 9:00 for four weeks") by calling book in a loop and collecting the errors.
  • Add days off to Doctor and refuse bookings on them, using calendar.component(.weekday, from:).
  • Replace the in-memory save with a file through FileManager (files and I/O) or a storage protocol like the one in the to-do project.
  • Make Schedule an actor so several tasks can book at once without a data race (actors).
  • Write tests for the boundary cases: a booking that ends exactly at closing time, and two bookings that touch.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Two half-open slots [a, b) and [c, d) overlap exactly when...

    Each must start before the other ends. With strict comparisons, a slot that ends exactly when the next begins does not overlap it, so back-to-back appointments are allowed.
  2. 2. Why does book(doctor:patient:at:now:) take the current time as a parameter?

    A function that reads the clock itself gives different answers at different times. Passing now in lets tests and examples fix the time.
  3. 3. Why compute a slot's end with calendar.date(byAdding: .minute, ...) instead of start + minutes * 60?

    Date supports adding a TimeInterval, but the calendar knows about time-zone offsets and daylight-saving transitions. Use it whenever you mean calendar units.
  4. 4. What does dateEncodingStrategy = .iso8601 change when saving the schedule?

    The default writes a number of seconds from a reference date. ISO 8601 is readable and understood by other systems, and the same strategy must be set on the decoder.
  5. 5. After cancelling and re-saving, why do new appointment ids not repeat old ones?

    The counter is part of the Codable state and is never decremented, so a cancelled id is never reused.

Summary

  • Model time ranges as half-open intervals and test overlap with two strict comparisons.
  • Use Calendar for every date computation, pin the time zone in examples, and pass "now" in as a parameter.
  • An error enum with associated values, thrown with typed throws, tells the caller exactly why a booking was refused.
  • A free-slot search is a walk from opening to closing that reuses the overlap rule.
  • Codable with the ISO 8601 date strategy saves and restores the whole schedule, including its id counter.

Next: Cheat Sheet