Test Swift business-day arithmetic on a cloud Mac

Test Swift business-day arithmetic on a cloud Mac

The delivery notice says “in three business days,” but the tests only cover adding three days to a Monday. Then a user places an order on a Friday, a holiday falls in the business region, and the calculated deadline ends up a day early. When you move a project to a cloud Mac, do not rely on the machine’s current regional settings. Make the business calendar, nonworking days, and counting rules explicit inputs, then run a standalone Swift regression fixture.

Define the business-day contract first

This article deals with civil dates, not business hours. The rules are fixed: use the Gregorian calendar and the business time zone, treat Saturday and Sunday as nonworking days, and inject additional holidays through a set. Adding a day excludes the starting date; negative offsets search backward; a zero offset preserves the original date without rolling it forward.

All results use local noon solely as an internal representation for date arithmetic. Do not treat that value as the actual order deadline. To establish a real deadline, separately combine the date with the close-of-business time and define how to handle nonexistent or repeated local times.

A “calendar day” is not a fixed number of seconds. Adding days through calendar components does not guarantee that every business rule is correct, but it avoids mistaking daylight saving time changes for date offsets.

Holiday data must identify its region, applicable year, and revision. This article uses a handcrafted fixture; the example set does not represent any region’s actual holiday schedule. If data for the target year is missing, the production entry point should report an error rather than assume there are no holidays that year.

Build a runnable date-arithmetic core

Create BusinessDays.swift outside the project directory on the cloud Mac, and first record the toolchain with xcrun swift --version. The following code depends only on Foundation from the system development tools. No dependencies need to be downloaded.

Extract date keys using the same business calendar throughout. Do not mix in a string formatter that uses the default time zone when checking dates. Apply separate limits to the offset and the number of days scanned: the first bounds the size of a request, while the second prevents an abnormal holiday configuration from causing a long-running loop.

import Foundation

struct Day: Hashable {
    let year: Int
    let month: Int
    let day: Int

    init(_ year: Int, _ month: Int, _ day: Int) {
        self.year = year
        self.month = month
        self.day = day
    }
}

enum RuleError: Error {
    case invalidInput
    case searchLimit
}

struct BusinessDays {
    let calendar: Calendar
    let holidays: Set<Day>

    init(zone: TimeZone, holidays: Set<Day>) {
        var calendar = Calendar(identifier: .gregorian)
        calendar.timeZone = zone
        self.calendar = calendar
        self.holidays = holidays
    }

    func key(_ date: Date) -> Day {
        let c = calendar.dateComponents(
            [.year, .month, .day], from: date
        )
        return Day(c.year!, c.month!, c.day!)
    }

    func date(_ day: Day) throws -> Date {
        let c = DateComponents(
            year: day.year, month: day.month,
            day: day.day, hour: 12
        )
        guard let result = calendar.date(from: c),
              key(result) == day else {
            throw RuleError.invalidInput
        }
        return result
    }

    func isWorking(_ date: Date) -> Bool {
        let weekday = calendar.component(.weekday, from: date)
        return weekday != 1 && weekday != 7
            && !holidays.contains(key(date))
    }

    func adding(_ offset: Int, to start: Day) throws -> Day {
        guard (-1000...1000).contains(offset) else {
            throw RuleError.invalidInput
        }
        var cursor = try date(start)
        var remaining = abs(offset)
        let step = offset < 0 ? -1 : 1

        for _ in 0..<3660 {
            if remaining == 0 { return key(cursor) }
            guard let next = calendar.date(
                byAdding: .day, value: step, to: cursor
            ) else {
                throw RuleError.invalidInput
            }
            cursor = next
            if isWorking(cursor) { remaining -= 1 }
        }

        guard remaining == 0 else {
            throw RuleError.searchLimit
        }
        return key(cursor)
    }
}

Checking the range before calling abs avoids the problem of taking the absolute value of the minimum integer. Reading the fields back after constructing a date rejects invalid dates that the calendar has automatically normalized. When loading the holiday set for production, validate every entry with date as well; validating only the starting date is not enough.

Cover forward, backward, and month-boundary cases with a synthetic holiday

Append the following fixture to the same file. It explicitly sets the business time zone and marks an otherwise ordinary Tuesday as a synthetic holiday. This checks whether the algorithm actually skips holidays rather than just weekends.

let zone = TimeZone(identifier: "Asia/Tokyo")!
let rules = BusinessDays(
    zone: zone,
    holidays: [Day(2030, 1, 8)]
)

func expect(_ start: Day, _ offset: Int, _ expected: Day) throws {
    let actual = try rules.adding(offset, to: start)
    precondition(actual == expected, "Business-day mismatch")
}

try expect(Day(2030, 1, 7), 1, Day(2030, 1, 9))
try expect(Day(2030, 1, 9), -1, Day(2030, 1, 7))
try expect(Day(2030, 1, 12), 0, Day(2030, 1, 12))
try expect(Day(2030, 1, 12), 1, Day(2030, 1, 14))
try expect(Day(2030, 1, 31), 2, Day(2030, 2, 4))

Run xcrun swift BusinessDays.swift. An exit code of zero means these checks passed. Keep precondition here rather than replacing it with a regular assert, which may be removed in an optimized build. Likewise, do not pipe the output through a formatter and lose the original exit code.

Next, add rejection tests for invalid months and days, out-of-range offsets, and long stretches of consecutive holidays. For cases that are expected to throw, check the error enum case. An unexpected success must fail the test; do not silently swallow every error with try?.

Use invariants to find coverage gaps, not to duplicate the implementation

In addition to checking fixed expected answers, iterate over a range of dates. For every nonzero offset, verify that the result is a working day and check its direction: a positive offset must produce a date after the start, and a negative offset must produce a date before it. Keep using the business calendar for these comparisons rather than the device defaults.

“Add three days, then subtract three days to return to the start” only holds when the starting date is itself a working day. Starting on a Saturday, adding one day takes you to Monday, but subtracting one day then takes you to Friday. If the test treats that result as incorrect, its contract is less precise than the implementation.

Add a monotonicity check as well: under the same rules, adding four business days must produce a later date than adding three business days. Work out expected answers by manually listing the working days traversed, so the tests and implementation do not share the same faulty loop.

Preserve configuration and failure evidence during integration

Once the standalone fixture passes, move the core into the business module and reuse that same implementation in the test target. Callers should pass only a date and an offset. Do not reimplement an “add two more days if it lands on a weekend” patch in the UI layer.

For every regression run, record the commit ID, toolchain, time zone identifier, holiday configuration version, starting date, offset, and actual result. When a test fails, first list the scan trace day by day to determine whether the problem lies in the configuration or the counting logic. Only then decide whether to change the algorithm.

Finally, store civil dates as explicit year, month, and day fields, or use an established date interchange protocol with a strict format. Do not pass the internal noon timestamp directly to a display in another time zone. Acceptance means that the same business input produces the same result regardless of the remote desktop’s regional settings, and that missing configuration, invalid dates, and search-limit violations all fail explicitly.

Frequently asked questions

Does adding one business day include the starting date?

Not in this contract. Counting begins on the following calendar date. A zero offset preserves the original civil date, even on a weekend or holiday.

How should exceptional working weekends be represented?

Add an explicit working-date set and define exception precedence. Reject configurations that list the same date as both working and nonworking.

Cloud Mac rentals by project term

Get an entire physical Mac mini for your exclusive use—not a virtual machine. Choose daily, weekly, monthly, or quarterly billing. It shuts down at the end of your term, with no automatic renewal or charges.

Choose a configuration and rental term

Choose your rental term, then start coding

Exclusive use of a physical Mac mini, billed daily, weekly, monthly, or quarterly. It shuts down at the end of your term, with no automatic renewal or charges.