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

Swift中如何通过任意索引集合选取数组子集的最简方法?

Swift数组获取非连续索引子集的实现方法

方法一:直接用map遍历索引数组

这是最直接简单的方式,不用扩展,直接遍历目标索引数组,逐个取出对应元素:

let myArray = ["first", "second", "third", "fourth"]
let targetIndices = [0, 2]
let subset = targetIndices.map { myArray[$0] }
// 输出结果:["first", "third"]

方法二:给Array扩展自定义下标,实现myArray[[0,2]]语法

如果想要像你期望的那样用myArray[[0,2]]这种写法,可以给Array扩展一个支持索引数组的下标:

extension Array {
    subscript(indices: [Int]) -> [Element] {
        indices.map { self[$0] }
    }
}

// 调用示例
let myArray = ["first", "second", "third", "fourth"]
let subset = myArray[[0, 2]]
// 输出结果:["first", "third"]

如果担心传入的索引越界崩溃,可以扩展一个安全版本的下标,自动校验索引有效性:

extension Array {
    subscript(safeIndices indices: [Int]) -> [Element]? {
        // 先过滤出有效的索引
        let validIndices = indices.filter { $0 >= 0 && $0 < count }
        // 如果有无效索引,返回nil;否则返回对应元素数组
        guard validIndices.count == indices.count else { return nil }
        return validIndices.map { self[$0] }
    }
}

// 安全调用示例
if let subset = myArray[safeIndices: [0, 2]] {
    print(subset) // ["first", "third"]
}

方法三:用compactMap自动忽略越界索引

如果你的索引数组可能包含无效值,又不想写扩展,可以用compactMap自动过滤掉越界的索引:

let myArray = ["first", "second", "third", "fourth"]
let targetIndices = [0, 2, 4] // 4是越界索引
let subset = targetIndices.compactMap { $0 < myArray.count && $0 >= 0 ? myArray[$0] : nil }
// 输出结果:["first", "third"],自动忽略了越界的索引4

内容的提问来源于stack exchange,提问作者vonbecker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 15:43:26