import Foundation
// Return all last Sundays of each month in a given year
struct LastSundaysOfYear: Sequence, IteratorProtocol {
let year: Int
private var month: Int
init(year: Int) {
self.year = year
self.month = 1
}
mutating func next() -> Date? {
guard month <= 12 else { return nil }
let calendar = Calendar.current
// Last day of the month
let comps = DateComponents(year: year, month: month + 1, day: 0)
var date = calendar.date(from: comps)!
// Walk backward to Sunday
while calendar.component(.weekday, from: date) != 1 { // Sunday = 1
date = calendar.date(byAdding: .day, value: -1, to: date)!
}
month += 1
return date
}
}
// Main
let args = CommandLine.arguments
let year: Int =
args.count > 1
? Int(args[1]) ?? 2026
: 2026
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
for date in LastSundaysOfYear(year: year) {
print(formatter.string(from: date))
}
/*
run:
01/25/2026
02/22/2026
03/29/2026
04/26/2026
05/31/2026
06/28/2026
07/26/2026
08/30/2026
09/27/2026
10/25/2026
11/29/2026
12/27/2026
*/