Swift数组中是否存在基于where子句返回最后索引的函数?
获取Swift数组中符合条件的最后一个元素索引
嘿,其实你想要的lastIndex(where:)在Swift 4.2及以后的版本里是原生支持的!你写的示例代码其实完全可以直接运行,不用自己折腾替代方案~
直接用系统内置方法的示例:
let array = [1, 2, 3, 4, 5, 3, 6] let indexOfLastElementEquals3 = array.lastIndex(where: { $0 == 3 }) print(indexOfLastElementEquals3) // 输出 Optional(5)
如果你的项目还在使用Swift 4.2之前的版本,也可以自己实现类似的功能,这里提供两种实用的替代方案:
方案一:反向遍历索引(直观高效)
手动从数组最后一个元素往前遍历,找到第一个符合条件的元素就返回其索引:
// 自定义扩展方法,方便复用 extension Array { func customLastIndex(where condition: (Element) -> Bool) -> Int? { for index in stride(from: count - 1, through: 0, by: -1) { if condition(self[index]) { return index } } return nil } } // 使用示例 let array = [1, 2, 3, 4, 5, 3, 6] if let index = array.customLastIndex(where: { $0 == 3 }) { print(index) // 输出 5 }
方案二:利用反向数组+索引转换
借助reversed()获取反向数组,找到符合条件的第一个元素的反向索引,再转换为原数组的索引:
let array = [1, 2, 3, 4, 5, 3, 6] if let reversedIndex = array.reversed().firstIndex(where: { $0 == 3 }) { // 将反向索引转换为原数组的索引 let originalIndex = array.index(array.endIndex, offsetBy: -reversedIndex.encodedOffset - 1) print(originalIndex) // 输出 5 }
两种方案里,第一种逻辑更直观,性能也更优(找到目标就停止遍历);第二种则更贴近系统API的写法,适合喜欢用系统方法的场景。
内容的提问来源于stack exchange,提问作者Roberto Sampaio
相关产品推荐
相关产品推荐

