I'm trying to write some program that calculates Age from the current date. The main rule is: BirthDate should be a Structure nested in Class
How do I write an initializer for that?
for example what I want to see: let myStudent = StudentClass(name: "John", age: BirthDate(10, 10, 1995), gpa: 3.3) will save myStudent.age 10.10.1995 as 26
class StudentClass {
var name: String
var age: UInt8
var gpa: Double
struct BirthDate {
var day: UInt8
var month: UInt8
var year: UInt16
var calculatedAge: UInt8 {
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let currYear = UInt16(components.year!)
let currMonth = components.month
let currDay = components.day
return UInt8(currYear - year) //it's not finished yet, just testing
}
}
init(name: String, age: (day: UInt8, month: UInt8, year: UInt16), gpa: Double) {
self.name = name
self.age = BirthDate.init(day: day, month: month, year: year)
self.gpa = gpa
}
}
CodePudding user response:
import Foundation
class StudentClass {
var name: String
var age: UInt8
var gpa: Double
struct BirthDate {
let day: UInt8
let month: UInt8
let year: UInt16
var calculatedAge: UInt8 {
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let currYear = UInt16(components.year!)
let currMonth = components.month
let currDay = components.day
return UInt8(currYear - year) // write your age calculator code here
}
}
init(name: String, birthDate: BirthDate, gpa: Double) {
self.name = name
self.age = birthDate.calculatedAge
self.gpa = gpa
}
}
//Example
let aStudent = StudentClass(name: "John Doe", birthDate: StudentClass.BirthDate(day: 1,month: 01,year: 1991), gpa: 8)
print(aStudent.age)
CodePudding user response:
Based on the code you provided, there is no need to create instance of BirthDate
just to calculate age and assign it to age property. You can make your age property lazy
that means it does not have to be instantiated at init
but it will be instantiated when you first use it.
class StudentClass {
var name: String
lazy var age: UInt8 = calculatedAge
var gpa: Double
var calculatedAge: UInt8 {
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let currYear = UInt16(components.year!)
let currMonth = components.month
let currDay = components.day
let year: UInt16 = 2021 //lets say
return UInt8(currYear - year) //it's not finished yet, just testing
}
init(name: String, age: (day: UInt8, month: UInt8, year: UInt16), gpa: Double) {
self.name = name
self.gpa = gpa
}
}