【问题标题】:Check if Date from Array of Dates is Date in Today (Swift)检查日期数组中的日期是否是今天的日期(Swift)
【发布时间】:2017-05-28 19:57:43
【问题描述】:

我有一系列“提醒”。 Reminder 是我自己编写的一个自定义类,它有一个属性 .fireDate。

如何检查提醒 .fireDate 属性之一是否与今天相同?

【问题讨论】:

  • 编辑您的问题并在此处粘贴相关代码

标签: ios arrays swift class date


【解决方案1】:
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
for (idx, date) in dates.enumerated() {
    if calendar.isDateInToday(date) {
        print("today at index \(idx)!")
    }
}

【讨论】:

  • 谢谢!以及如何获取与数组中日期匹配的对象的索引?
  • 只需使用enumerated()函数:)
【解决方案2】:

获取fireDate 在今天的第一个项目的索引。如果不是nil,则至少有一项。

let calendar = Calendar.current
if let indexOfFirstReminderWhichFiresToday = reminders.index(where: { calendar.isDateInToday($0.fireDate) }) {
    print("\(reminders[indexOfFirstReminderWhichFiresToday]) fires today")
}

【讨论】:

  • 改用contains(where:)
  • 谢谢,太棒了!不知道有没有这样的方法^^
  • != nil 糟透了。有guardsif let 可以避免使用nil。 :)
  • @Alexander OP 似乎还需要该项目的索引。
猜你喜欢
  • 2018-04-05
  • 1970-01-01
  • 2020-10-21
  • 2016-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-26
  • 2014-09-13
相关资源
最近更新 更多