Swift 5中DateValue枚举解析:如何获取Foundation.Date实例
解决DateValue枚举转Foundation.Date的问题
为什么强制转换失败
DateValue是自定义枚举类型,它的两个case仅将Date作为关联值存储,本身和Foundation.Date没有继承或桥接关系,因此theStartDate as Date这类强制转换必然失效。
解决方案
方案1:给DateValue添加计算属性(推荐)
给DateValue扩展一个计算属性,直接返回关联的Date值:
extension DateValue { var underlyingDate: Date { switch self { case .dateOnly(let date), .dateAndTime(let date): return date } } }
使用时直接调用属性:
let startDate = theStartDate.underlyingDate
在Xcode调试器控制台也可直接查看:
po theStartDate.underlyingDate
方案2:直接用Switch语句提取
若不想扩展原类型,可通过匹配枚举case直接提取Date:
let startDate: Date switch theStartDate { case .dateOnly(let date): startDate = date case .dateAndTime(let date): startDate = date }
方案3:扩展Date添加初始化器
给Date扩展一个接收DateValue的初始化方法:
extension Date { init(from dateValue: DateValue) { switch dateValue { case .dateOnly(let date), .dateAndTime(let date): self = date } } }
使用时:
let startDate = Date(from: theStartDate)
内容的提问来源于stack exchange,提问作者John R
相关产品推荐
相关产品推荐

