SwiftUI中Foundation.Date与自定义Date类型转换错误求助
问题原因与解决方案
错误原因
你自定义的Date结构体和系统Foundation框架中的Date类型重名,导致编译器混淆了两个类型:Calendar.current.date(from:)返回的是系统的Foundation.Date,但你的自定义函数声明返回的是你自己的BarCharts.Date(BarCharts是你的项目模块名),类型不匹配所以报错。
解决办法
方法1:重命名自定义Date(推荐)
直接给自定义结构体改个名字,避免和系统类型冲突,比如AppDate或CustomDate:
struct ViewMonth: Identifiable { let id = UUID() let date: Date // 这里自动指向系统Foundation.Date let viewCount: Int } struct AppDate { static func from(year: Int, month: Int, day: Int) -> Date { let components = DateComponents(year: year, month: month, day: day) return Calendar.current.date(from: components)! } }
方法2:明确区分两个Date类型
如果不想修改自定义结构体名称,就通过模块名或框架名明确指定类型:
struct ViewMonth: Identifiable { let id = UUID() let date: BarCharts.Date // 明确使用自定义的Date let viewCount: Int } struct Date { static func from(year: Int, month: Int, day: Int) -> Foundation.Date { // 明确返回系统Foundation.Date let components = DateComponents(year: year, month: month, day: day) return Calendar.current.date(from: components)! } }
方法3:让自定义Date包装系统Date
如果需要自定义Date持有系统Date的功能,可以调整结构体设计:
struct Date { let foundationDate: Foundation.Date static func from(year: Int, month: Int, day: Int) -> Date { let components = DateComponents(year: year, month: month, day: day) guard let foundationDate = Calendar.current.date(from: components) else { fatalError("Invalid date components") } return Date(foundationDate: foundationDate) } } struct ViewMonth: Identifiable { let id = UUID() let date: Date let viewCount: Int }
内容的提问来源于stack exchange,提问作者yitak lee
相关产品推荐
相关产品推荐

