You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中Rosa结构体日期初始化与自动计算年龄问题

解决方案

1. 重构结构体,实现自动计算年龄与格式化日期

我们可以通过计算属性实现年龄自动推导,同时新增格式化属性来展示指定格式的出生日期,无需手动维护这两个字段。

修改后的完整代码:

import Foundation

struct Rosa: Identifiable, Hashable, Equatable {
    let id = UUID()
    let stagione: String
    let nomeGiocatore: String
    let cognomeGiocatore: String
    let nascitaGiocatore: Date
    let ruoloGiocatore: String
    
    // 自动计算年龄:当前年份减去出生年份
    var etàGiocatore: Int {
        let calendar = Calendar.current
        let currentYear = calendar.component(.year, from: Date())
        let birthYear = calendar.component(.year, from: nascitaGiocatore)
        return currentYear - birthYear
    }
    
    // 格式化出生日期为「dd-MM-yyyy」格式的字符串
    var nascitaGiocatoreFormattata: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "dd-MM-yyyy"
        // 可选:设置意大利本地化,避免区域格式干扰
        formatter.locale = Locale(identifier: "it_IT")
        return formatter.string(from: nascitaGiocatore)
    }
    
    // 简化初始化方法:移除年龄参数,因为年龄自动计算
    init(stagione: String, nomeGiocatore: String, cognomeGiocatore: String, nascitaGiocatore: Date, ruoloGiocatore: String) {
        self.stagione = stagione
        self.nomeGiocatore = nomeGiocatore
        self.cognomeGiocatore = cognomeGiocatore
        self.nascitaGiocatore = nascitaGiocatore
        self.ruoloGiocatore = ruoloGiocatore
    }
    
    static func testRosa() -> [Rosa] {
        // 正确创建测试用的Date对象
        let formatter = DateFormatter()
        formatter.dateFormat = "MM/dd/yyyy"
        let birthDate = formatter.date(from: "03/31/2000")!
        
        return [Rosa(
            stagione: "2023/2024",
            nomeGiocatore: "Matt",
            cognomeGiocatore: "Bar",
            nascitaGiocatore: birthDate,
            ruoloGiocatore: "Portiere"
        )]
    }
}

2. 关键修改说明

  • 自动计算年龄:借助Calendar获取当前年份与出生年份的差值,每次访问etàGiocatore时都会自动更新,无需手动传入或维护。
  • 格式化日期展示:新增nascitaGiocatoreFormattata计算属性,用DateFormatter将Date类型转换为指定格式的字符串(注意用小写yyyy表示公历年份,大写YYYY是周年概念,日常场景用小写更准确)。
  • 修正测试数据:原代码中03/31/2000是除法运算(结果为0.000375),不是合法的Date对象。我们通过DateFormatter将字符串转换为正确的Date。
  • 简化初始化:移除了etàGiocatore的初始化参数,因为年龄由出生日期自动推导,不需要外部传入。

3. 使用示例

展示时直接调用对应的属性即可:

let giocatore = Rosa.testRosa().first!
print(giocatore.nascitaGiocatoreFormattata) // 输出「31-03-2000」
print(giocatore.etàGiocatore) // 输出当前年份与2000的差值,比如2024年输出24

内容的提问来源于stack exchange,提问作者AndreB82

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 05:35:05