isLeapYear() in Swift

Updated: 20161208 to Swift 3

Since 2016 is a leap year, I decided that I need to have a couple of handy functions to determine if a given year is a leap year. I wrote two functions. The first function takes an integer year and returns a boolean. The second isLeapYear() method calls the first. It takes an optional NSDate value. If no date is provided, it defaults to today.

isLeapYear(1900) // false
isLeapYear(2000) // true
isLeapYear(2015) // false
isLeapYear(2016) // true

let now = Date()
isLeapYear(now)
isLeapYear() // Default parameter is Date()

Here’s the rest of the playground code:

import Foundation

func isLeapYear(_ year: Int) -> Bool {
    
    let isLeapYear = ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
    
    
    return isLeapYear
}

func isLeapYear(_ date: Date = Date()) -> Bool {
    
    let calendar = NSCalendar.current
    let components = calendar.dateComponents([.year], from: date)
    
    let year = components.year
    return isLeapYear(year!)
}


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s