Skip to content

Instantly share code, notes, and snippets.

@matthewspear
Created April 28, 2016 18:16
Show Gist options
  • Save matthewspear/be583fd18271ad4c50d7d4ea622b4b11 to your computer and use it in GitHub Desktop.
Save matthewspear/be583fd18271ad4c50d7d4ea622b4b11 to your computer and use it in GitHub Desktop.
Example using a lazy variable as a first class citizen + date formatters!
import UIKit
class Person
{
let name: String
let birthday: NSDate
lazy var age: Double = self.calculateAge()
init(name: String, birthday: NSDate)
{
self.name = name
self.birthday = birthday
}
init(name: String, birthday: String)
{
self.name = name
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
self.birthday = dateFormatter.dateFromString(birthday)!
}
func calculateAge() -> Double
{
let diff = NSDate().timeIntervalSinceDate(birthday)
//estimate of seconds in a year (not including leap years)
let years = Double(diff) / 31536000
return years
}
}
let matt = Person(name: "Matthew", birthday: "24/10/1993")
matt.age
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment