Swift Program to Join Two Strings

1. Introduction

Leap years are a fascinating aspect of the Gregorian calendar, introduced to keep our calendar year synchronized with the astronomical or seasonal year. Essentially, a leap year contains one additional day. In this guide, we'll see how to determine if a given year is a leap year using Swift.

2. Program Overview

A leap year occurs:

1. Every year that is divisible by 4

2. Except for years that are divisible by 100

3. However, years divisible by 400 are also leap years

We'll create a Swift function that implements this logic to check if a given year is a leap year.

3. Code Program

// 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
    }
}

// Testing the function
let year = 2020
if isLeapYear(year) {
    print("\(year) is a leap year.")
} else {
    print("\(year) is not a leap year.")
}

Output:

2020 is a leap year.

4. Step By Step Explanation

1. We start by defining the isLeapYear(_:) function that takes an integer as its argument (representing the year) and returns a boolean indicating if it's a leap year.

2. Within the function:

- We first check if the year is divisible by 400 using the condition year % 400 == 0. If true, it's a leap year.

- Next, we ensure it's not a century year that isn't divisible by 400 using the condition year % 100 == 0.- If neither of the above conditions is met, we simply check if the year is divisible by 4 using year % 4 == 0.

3. After defining the function, we test it using the year 2020 and then display the result based on the return value of the function.

Using this straightforward logic, one can efficiently determine if a given year is a leap year in Swift.


Comments