Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift: How to insert a getter in computed property to calculate a person's age

I have written the following computed property to calculate the age of the app user:

var ageCalc: Int {
    let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
    let now = Date()
    let calcAge = calendar.components(.year, from: userData.birthdate, to: now, options: [])
    let age = calcAge.year
}

The compiler error I receive is:

"Missing return in getter expected to return ‘Int’"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

getterError

Adding "return age" gives a slew of errors:

returnAgeCode

returnAgeError

>Solution :

Using Calendar instead of the old NSCalendar you can write the property as

var ageCalc: Int {
    Calendar(identifier: .gregorian).dateComponents([.year], from: userData.birthdate, to: .now).year!
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading