How to print every month in a specified year that contains five full weekends (Fri, Sat, Sun) in Swift

1 Answer

0 votes
// A month has five full weekends when it has 31 days,
// and the 1st day of the month is a Friday.

import Foundation

// ------------------------------------------------------------
// Month names as a single reusable constant
// ------------------------------------------------------------
let monthNames: [String] = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
]

// ------------------------------------------------------------
// Function: returns true if a month has 5 full weekends
// ------------------------------------------------------------
func hasFiveFullWeekends(year: Int, month: Int) -> Bool {
    var components = DateComponents()
    components.year = year
    components.month = month
    components.day = 1

    let calendar = Calendar.current

    guard let firstDay = calendar.date(from: components),
          let daysRange = calendar.range(of: .day, in: .month, for: firstDay) else {
        return false
    }

    let daysInMonth = daysRange.count
    let weekday = calendar.component(.weekday, from: firstDay) // Sunday=1 ... Friday=6

    return (daysInMonth == 31 && weekday == 6) // Friday
}

// ------------------------------------------------------------
// Main program
// ------------------------------------------------------------
func main() {
    let yValue = 2026

    for m in 1...12 {
        if hasFiveFullWeekends(year: yValue, month: m) {
            print("\(monthNames[m - 1]) \(yValue) has five full weekends.")
        }
    }
}

main()



/*
run:

May 2026 has five full weekends.

*/

 



answered May 27 by avibootz

Related questions

...