You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:05:44