Swift – Check Leap Year
In this tutorial, we will learn how to check if a given year is a leap year in Swift. Leap years occur every 4 years, except for years that are divisible by 100 but not divisible by 400. We will implement a simple function to determine if a year is a leap year and handle edge cases.
What is a Leap Year?
A leap year is a year that contains an extra day, February 29, to keep the calendar year synchronized with the astronomical year. The rules to determine a leap year are:
- A year is a leap year if it is divisible by 4.
- However, if the year is divisible by 100, it is not a leap year unless it is also divisible by 400.
For example:
2000
is a leap year because it is divisible by 400.1900
is not a leap year because it is divisible by 100 but not by 400.2024
is a leap year because it is divisible by 4.
Algorithm to Check Leap Year
- If the year is divisible by 400, it is a leap year.
- If the year is divisible by 100 but not by 400, it is not a leap year.
- If the year is divisible by 4 but not by 100, it is a leap year.
- Otherwise, it is not a leap year.
Using this logic, we can create a function to determine if a year is a leap year.
Implementing Leap Year Check in Swift
Here’s a simple function to check if a year is a leap year:
func isLeapYear(_ year: Int) -> Bool {
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 = 2024
if isLeapYear(year) {
print("\(year) is a leap year.")
} else {
print("\(year) is not a leap year.")
}
Explanation:
year % 400 == 0
: Checks if the year is divisible by 400.year % 100 == 0
: Excludes years that are divisible by 100 but not 400.year % 4 == 0
: Identifies years that are divisible by 4 but not by 100.
Handling Edge Cases
The function handles edge cases such as:
2000
: A leap year (divisible by 400).1900
: Not a leap year (divisible by 100 but not by 400).2023
: Not a leap year (not divisible by 4).
Complete Swift Program
Here’s the complete program to check if a year is a leap year:
main.swift
import Foundation
// Function to check if a year is a leap year
func isLeapYear(_ year: Int) -> Bool {
if year % 400 == 0 {
return true
} else if year % 100 == 0 {
return false
} else if year % 4 == 0 {
return true
} else {
return false
}
}
// Test cases
let years = [2000, 1900, 2023, 2024, 2100]
for year in years {
if isLeapYear(year) {
print("\(year) is a leap year.")
} else {
print("\(year) is not a leap year.")
}
}
Output:
2000 is a leap year.
1900 is not a leap year.
2023 is not a leap year.
2024 is a leap year.
2100 is not a leap year.
Program ended with exit code: 0
This program efficiently checks if a given year is a leap year, adhering to the rules of the Gregorian calendar.