Back to Blog

Swift: Is 2023 a leap year?

Sandy LaneSandy Lane

Video: Swift: Is 2023 a leap year? by Taught by Celeste AI - AI Coding Coach

Watch full page →

Swift: Is 2023 a Leap Year?

Determining whether a given year is a leap year is a common programming task that involves checking specific rules related to the Gregorian calendar. In Swift, you can implement a simple function to check if a year like 2023 is a leap year by applying these rules directly.

Code

func isLeapYear(_ year: Int) -> Bool {
  // A year is a leap year if it is divisible by 4,
  // except for years divisible by 100,
  // unless they are also divisible by 400.
  if year % 400 == 0 {
    return true
  } else if year % 100 == 0 {
    return false
  } else if year % 4 == 0 {
    return true
  } else {
    return false
  }
}

// Example usage:
let year = 2023
if isLeapYear(year) {
  print("\(year) is a leap year.")
} else {
  print("\(year) is not a leap year.")
}

Key Points

  • Leap years occur every 4 years, but century years must be divisible by 400 to qualify.
  • The function uses modular arithmetic to apply the leap year rules clearly and efficiently.
  • 2023 is not a leap year because it is not divisible by 4.
  • Swift’s concise syntax makes it easy to implement calendar logic in a readable way.