Search code examples
swiftdate

Initialize date variable and calculate age


I have the following data structure in my project. Basically I have two variables that I'm not able to set up:

import Foundation

struct Rosa: Identifiable, Hashable, Equatable {
    let id = UUID()
    let stagione: String
    let nomeGiocatore: String
    let cognomeGiocatore: String
    let nascitaGiocatore: Date
    let etàGiocatore: Int
    let ruoloGiocatore: String
    
    init(stagione: String, nomeGiocatore: String, cognomeGiocatore: String, nascitaGiocatore: Date, etàGiocatore: Int, ruoloGiocatore: String) {
        self.stagione = stagione
        self.nomeGiocatore = nomeGiocatore
        self.cognomeGiocatore = cognomeGiocatore
        self.nascitaGiocatore = nascitaGiocatore
        self.etàGiocatore = etàGiocatore
        self.ruoloGiocatore = ruoloGiocatore
        
        nascitaGiocatore.formatted(date: .numeric, time: .omitted)
    }
    
    static func testRosa() -> [Rosa] {
        [Rosa(stagione: "2023/2024", nomeGiocatore: "Matt", cognomeGiocatore: "Bar", nascitaGiocatore: 03/31/2000, etàGiocatore: 23, ruoloGiocatore: "Portiere")]
    }
}

I'd like to have "nascitaGiocatore" in the format "dd-MM-YYYY" and "etàGiocatore" as the difference between current year and "nascitaGiocatore" year. But I'm completely stuck.


Solution

  • you can use a DateFormatter to parse the birth date string in the testRosa method. It should be something like below:

    static func testRosa() -> [Rosa] {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "dd-MM-yyyy"
            let birthDate = dateFormatter.date(from: "31-03-2000")!
            
            let currentYear = Calendar.current.component(.year, from: Date())
            let birthYear = Calendar.current.component(.year, from: birthDate)
            let age = currentYear - birthYear
            
            return [Rosa(stagione: "2023/2024", nomeGiocatore: "Matt", cognomeGiocatore: "Bar", nascitaGiocatore: birthDate, etàGiocatore: age, ruoloGiocatore: "Portiere")]
        }
    

    Also you don't need to format 'nascitaGiocatore' at the init function. It seemed unnecessary. You can remove it.