【问题标题】:Getting the first index of an array of objects using a property - swift使用属性获取对象数组的第一个索引 - swift
【发布时间】:2021-07-24 18:08:27
【问题描述】:

我有一个名为modelArray 的对象数组,这些对象有一个名为timestamp 的属性,其类型为FIRTimestamp

知道我们还有另一个时间戳,我们将称之为 comparingTimestamp

我试图弄清楚如何在数组中找到属性timestamp>comparingTimestamp 的第一个索引。

如果您不熟悉 firebase,对象 Timestamp 有一个名为 seconds 的数字属性,我们可以使用它来进行比较。

直到现在我尝试使用函数where,但没有任何好的结果。

【问题讨论】:

  • 添加您的代码,向我们展示您到目前为止所做的尝试。
  • comparingTimestamp 的类型是什么?
  • 仍然是“FIRTimestamp”

标签: arrays swift firebase


【解决方案1】:

您可以使用集合的firstIndex(where:) 方法:


struct Item {
    let timestamp: FIRTimestamp
}

let modelArray = [item1, item2, item3, item4]
let firstIndex = modelArray.firstIndex { item in
    item.timestamp.seconds > comparingTimestamp.seconds
}

print(firstIndex!) 

【讨论】:

    猜你喜欢
    • 2020-05-21
    • 2022-11-27
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    • 2016-05-22
    • 2019-10-19
    • 2023-04-08
    相关资源
    最近更新 更多