3000 Swift Urls

I recently passed 3000 urls in my Swift Resources database. Over the weekend I added over a 100 YouTube videos. I haven’t tagged everything but I’ll work on it this week.

Since my last writeup in Sept, I’ve added Swift Today, Swift Weekly, and “Tags” pages, which shows all the tags and the tag count.


Finally, I also started a Swift Cookbook with topics that include Strings, Arrays, Dictionaries, and Dates. I’ll be working on additional Cookbook pages over the next few months.

Swift adoption by bloggers has been phenomenal. Most developers and book authors made a quick transition to Swift in the summer of 2014 with iOS 8. Thanks to the community it’s now easy to master iOS using Swift.


Swift: dateFromInt() and intFromDate()

Updated: 20161208 to Swift 3

I needed a couple of convenience functions to convert between NSDates and YYYYMMDD integer dates. Here are examples of each function call:

let d0 = dateFromInt(20160111)
let d1 = intFromDate(Date())

Here’s the source for dateFromInt():

//: Date from Int YYYYMMDD
func dateFromInt(_ date:Int) -> Date {
    let year = date / 10000
    let month = date % 10000 / 100
    let day = date % 100
    let components = NSDateComponents()
    components.year = year
    components.month = month
    components.day = day
    let aDate = NSCalendar(identifier: NSCalendar.Identifier.gregorian)?.date(from: components as DateComponents)
    return aDate!

Here’s intFromDate()

//: Date to Int YYYYMMDD
func intFromDate(_ date:Date) -> Int {
    let calendar = NSCalendar.current
    let components = calendar.dateComponents([.year, .month, .day], from: date)

    let year = components.year
    let month = components.month
    let day = components.day
    let intDate = year! * 10000 + month! * 100 + day!
    return intDate

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() // 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!)