Home > Software engineering >  Swift: How to insert a getter in computed property to calculate a person's age
Swift: How to insert a getter in computed property to calculate a person's age

Time:11-01

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'"

getterError

Adding "return age" gives a slew of errors:

returnAgeCode

returnAgeError

CodePudding user response:

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!
}
  • Related