swift - 在 Swift Array 中,是否有一个函数可以根据 where 子句返回最后一个索引?

标签 swift

Swift 数组的函数 index 根据 where 子句中的条件返回第一个元素。有没有办法得到这个条件下的最后一个元素?

例如,我想要这样的东西(我知道没有名为 lastIndex 的函数。这个函数或类似函数就是我要搜索的):

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

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

print(indexOfLastElementEquals3) //5 (Optional)

最佳答案

lastIndex(where:) 和相关方法是在 Swift 4.2 中添加的, 看

在较早的 Swift 版本中,您可以在相反的位置使用 index(where:) Collection View :

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:) 方法是必需的。

关于swift - 在 Swift Array 中,是否有一个函数可以根据 where 子句返回最后一个索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50279988/

相关文章:

ios - 泛型类类型不符合 Any

ios - swift 4: UITableView setSelected 函数在 iPad 上点击两次

json - 解析开头有定义的Json

ios - Swift 中的 CGPointMake

ios - 仅在 iOS 13.1 和 13.2 中弹出 View 后面有奇怪的阴影

swift - 限制查询函数中的多个打印语句

ios - 如何使用 Eureka 制作多行标签

ios - 仅在 swift 中右侧的 UITextField 边框

swift - 如何在 Swift 中将 block 引用应用于 UIWebView

ios - 不显示所有用户的用户数据,如何只显示喜欢该登录用户的人的数据?