Back to Blog

Swift: How many Friday the 13th

Sandy LaneSandy Lane

Video: Swift: How many Friday the 13th by Taught by Celeste AI - AI Coding Coach

Watch full page →

Swift: How Many Friday the 13ths in the Year 2023

In this example, we use Swift's Calendar and Date components to find how many times the 13th day of a month falls on a Friday in a given year. This is a practical way to work with dates and perform calendar calculations in Swift.

Code

import Foundation

func countFridayThe13ths(in year: Int) -> Int {
  let calendar = Calendar.current
  var count = 0

  // Iterate through all 12 months
  for month in 1...12 {
    // Create date components for the 13th day of the current month and year
    var components = DateComponents()
    components.year = year
    components.month = month
    components.day = 13

    // Get the date from components
    if let date = calendar.date(from: components) {
      // Get the weekday component (1 = Sunday, 6 = Friday)
      let weekday = calendar.component(.weekday, from: date)
      if weekday == 6 { // 6 corresponds to Friday in Gregorian calendar
        count += 1
      }
    }
  }
  return count
}

// Example usage:
let year = 2023
let fridayThe13ths = countFridayThe13ths(in: year)
print("Number of Friday the 13ths in \(year): \(fridayThe13ths)")

Key Points

  • Use Calendar and DateComponents to construct specific dates in Swift.
  • The weekday component returns an integer where 6 corresponds to Friday in the Gregorian calendar.
  • Iterate through each month to check if the 13th is a Friday.
  • This approach can be adapted to find other specific weekdays on any date.