【问题标题】:In Swift Array, is there a function that returns the last index based in where clause?在 Swift Array 中,是否有一个函数可以返回基于 where 子句的最后一个索引?
【发布时间】:2018-05-10 19:13:24
【问题描述】:

Swift 数组的 index 函数根据 where 子句中的条件返回第一个元素。有没有办法在这种情况下获取最后一个元素?

例如,我想要这样的东西(我知道没有名为 lastIndex 的函数。我正在寻找这个函数或类似的函数):

let array = [1, 2, 3, 4, 5, 3, 6]

let indexOfLastElementEquals3 = array.lastIndex(where: { $0 == 3 })

print(indexOfLastElementEquals3) //5 (Optional)

【问题讨论】:

标签: swift


【解决方案1】:

lastIndex(where:) 及相关方法在 Swift 4.2 中加入, 见

在早期的 Swift 版本中,您可以使用 index(where:) 反转 集合视图:

let array = [1, 2, 3, 4, 5, 3, 6]

if let revIndex = array.reversed().index(where: { $0 % 2 != 0 } ) {
    let indexOfLastOddElement = array.index(before: revIndex.base)
    print(indexOfLastOddElement) // 5
}

或作为单个表达式:

let indexOfLastOddElement =  array.reversed().index(where: { $0 % 2 != 0 } )
    .map { array.index(before: $0.base) }

print(indexOfLastOddElement) // Optional(5)

revIndex.base 返回位置revIndex 的位置之后 在底层集合中,这就是为什么我们必须“减去”一个 来自索引。

对于数组,这可以简化为

    let indexOfLastOddElement = revIndex.base - 1

但对于具有非整数索引的集合(如String) 以上index(before:)方法是需要的。

【讨论】:

  • @Sulthan:是的,数组索引是 Int。对于其他集合(如字符串),您需要 index(before:)
  • 这个目标是奇数假设他搜索偶数,也没有输入,它只用于这个用例
  • @Sh_Khan:对不起,我不明白你的意思。这里有什么问题吗?
  • 假设根据你的搜索最后一个数字6的索引,那么我们必须将$0 % 2 != 0更改为$0 % 2 == 0
  • 另一种方法是反转indices,例如array.indices.reversed().first(where: { array[$0] % 2 != 0 } )。这意味着您必须在谓词中进行下标,但另一方面您不必在之后调整返回的索引。
猜你喜欢
  • 1970-01-01
  • 2017-05-29
  • 2010-12-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-14
  • 2020-04-04
  • 2012-05-22
  • 1970-01-01
相关资源
最近更新 更多