Created
April 28, 2016 18:16
-
-
Save matthewspear/be583fd18271ad4c50d7d4ea622b4b11 to your computer and use it in GitHub Desktop.
Example using a lazy variable as a first class citizen + date formatters!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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