dateComponents 尝试计算年龄的问题(swiftUI)

issue with dateComponents trying to calculate age in years (swiftUI)

当我尝试根据今天的日期和生日计算某人的年龄时,出现 "Type 'Set' has no member 'year'" 错误:

let birthday = "10/08/1978"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"

let startDate = dateFormatter.date(from: birthday)
let endDate = Date()

let calendar = Calendar.current
let calcAge = calendar.dateComponents(.year, from: startDate!, to: endDate)
let age = calcAge.year

Xcode 让我把 calendar.components 改成了 calendar.dateComponents,但是 .year 马上开始报错。据我在开发人员文档中所知,.year 是有效的。但是开发者文档的 URL 说我正在查看 calendar.dateComponents,而实际页面上的标题说 calendar.components。这里有什么想法吗?谢谢!

您必须传递一组 DateComponents,因此调用将变为:

let calcAge = calendar.dateComponents([.year], from: startDate!, to: endDate)