How to find the dates of the last Fridays of each month of a given year in Swift

1 Answer

0 votes
import Foundation

// Return all last Fridays of each month in a given year
func lastFridaysOfYear(_ year: Int) -> AnySequence<Date> {
    let calendar = Calendar(identifier: .gregorian)

    return AnySequence<Date> {
        var month = 1

        return AnyIterator<Date> {   // <-- FIX: specify <Date>
            guard month <= 12 else { return nil }

            // Last day of the month
            let comps = DateComponents(year: year, month: month + 1, day: 0)
            var date = calendar.date(from: comps)!

            // Walk backward to Friday
            while calendar.component(.weekday, from: date) != 6 { // Friday = 6
                date = calendar.date(byAdding: .day, value: -1, to: date)!
            }

            month += 1
            return date
        }
    }
}

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 lastFridaysOfYear(year) {
    print(formatter.string(from: date))
}



/*
run:

01/30/2026
02/27/2026
03/27/2026
04/24/2026
05/29/2026
06/26/2026
07/31/2026
08/28/2026
09/25/2026
10/30/2026
11/27/2026
12/25/2026

*/



/*
run:

01/30/2026
02/27/2026
03/27/2026
04/24/2026
05/29/2026
06/26/2026
07/31/2026
08/28/2026
09/25/2026
10/30/2026
11/27/2026
12/25/2026

*/

 



answered 4 hours ago by avibootz

Related questions

...