按索引过滤数组 [英] Filter array by indices

查看:85
本文介绍了按索引过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列元素。我还有一个IndexSet,它指定需要将数组的哪些索引提取到新数组中。例如:

I have an array of elements. I also have an IndexSet that specifies which indices of the array need to be extracted into a new array. E.g.:

let array = ["sun", "moon", "star", "meteor"]
let indexSet: IndexSet = [2, 3]
// Some magic happens here to get:
let result = ["star", "meteor"]

我正在寻找使用swift 过滤器的功能,但尚未得到答案。我该怎么做?

I'm looking to use the swift filter function, but haven't got the answer yet. How can I do this?

推荐答案

IndexSet 是一个增加的集合整数,因此你可以
map 每个索引到相应的数组元素:

IndexSet is a collection of increasing integers, therefore you can map each index to the corresponding array element:

let array = ["sun", "moon", "star", "meteor"]
let indexSet: IndexSet = [2, 3]

let result = indexSet.map { array[$0] } // Magic happening here!
print(result) // ["star", "meteor"]

这假设所有索引对给定数组都有效。
如果不能保证,那么你可以过滤指数
(正如@dfri正确评论的那样):

This assumes that all indices are valid for the given array. If that is not guaranteed then you can filter the indices (as @dfri correctly remarked):

let result = indexSet.filteredIndexSet { $0 < array.count }.map { array[$0] }

这篇关于按索引过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆