Skip to content

Instantly share code, notes, and snippets.

@quangnd
Last active March 4, 2024 16:53
Show Gist options
  • Save quangnd/1fd0ff1d19062c10de7b868dc8b49fff to your computer and use it in GitHub Desktop.
Save quangnd/1fd0ff1d19062c10de7b868dc8b49fff to your computer and use it in GitHub Desktop.
Swift Learning - Tutor 1 - Leap year

Exercise 1 - Leap year

You are given a year, determine if it’s a leap year. A leap year is a year containing an extra day. It has 366 daysinstead of the normal 365 days. The extra day is added in February, which has 29 days instead of the normal 28 days. Leap years occur every 4 years. 2012 was a leap year and 2016 will also be a leap year.

The above rule is valid except that every 100 years special rules apply. Years that are divisible by 100 are not leap years if they are not also divisible by 400. For example 1900 was not a leap year, but 2000 was. Print Leap year! or Not a leap year! depending on the case.

Hint: Use the remainder (%) operator to check for divisibility by 4. Don’t forget to check the special case when year is divisible by 100.

let year = 2014
if year % 4 == 0 {
    if year % 100 == 0 && year % 400 != 0 {
        print("Not a leap year!")
    } else {
        print("Leap year!")
    }
} else {
    print(year, terminator: "-")
    print("Not a leap year!")
}
@zeljkobilbija
Copy link

func isLeapYear(datum: Date) -> Bool {
    let calendar = Calendar(identifier: .gregorian)
    let dateComponents = DateComponents(year: Int(calendar.component(.year, from: datum)), month: 2)
    let date = calendar.date(from: dateComponents)!
    let range = calendar.range(of: .day, in: .month, for: date)!
    let numDays = range.count
    
    if numDays == 29 {
        return true
    }else {
        return false
    }

}

@jrBordet
Copy link

jrBordet commented Dec 2, 2020

public struct Year {
    public let isLeapYear: Bool
    public var calendarYear: Int
    
    public init(calendarYear: Int) {
        self.calendarYear = calendarYear
        self.isLeapYear = Leap.isLeapYear(calendarYear)
    }
}

private func isLeapYear(_ y: Int) -> Bool {
    let df = DateFormatter()
    df.dateFormat = "yyyy-MM-dd"
        
    guard df.date(from: "\(String(y))-02-29") != nil else {
        return false
    }
    
    return true
}

let year = Year(calendarYear: 1997)
XCTAssertFalse(year.isLeapYear)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment