以下代码应返回自创建单元格以来的天数,但它也会返回 isLeapMonth: false
. 这是为什么?我该如何删除它?
let cell = super.tableView(tableView, cellForRowAt: indexPath)
cell.textLabel?.text = itemArray[indexPath.row].title
let startDate = itemArray[indexPath.row].dateCreated
let currentDate = Date()
let components = Set<Calendar.Component>([.day])
let differenceOfDate = Calendar.current.dateComponents(components, from: startDate!, to: currentDate)
cell.detailTextLabel?.text = "\(differenceOfDate)"
return cell
2 回答
这是因为
differenceOfDate
的类型为DateComponents
,这不会返回一个数字 . 如果您需要获取天数,可以通过DateComponents
获取day
属性来获取此数字由于您只需要天数,因此您应该从结果
DateComponents
中仅提取day
值并根据需要打印该数字 .请注意,在此处使用
!
是安全的,因为您特别请求了.day
组件 .