ios - 按索引过滤数组

标签 ios swift

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

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

我想使用 swift filter 函数,但还没有得到答案。我该怎么做?

最佳答案

IndexSet 是递增整数的集合,因此您可以 每个索引映射到相应的数组元素:

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 正确评论的那样):

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

关于ios - 按索引过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40264624/

相关文章:

ios - 基于C#程序的Swift电话词生成器实现

ios - XCode 6.3 向 tableviewcell 添加边距

Swift 3 - localPlayer auth 影响 SKSpriteNode 的 Action

ios - 对核心数据对象的更改未持久

ios - 通过触摸按钮显示广告横幅

ios - 将设备从一个 Apple 开发者帐户转移到另一个

iphone - iOS:如何在 iPad/iPhone 上以编程方式读取当前网络事件级别?

iphone - iOS 检查数据库是否已创建并在两个 .sqlite 文件之间进行选择以加载

multithreading - 线程+多个窗口导致奇怪的错误

ios - Swift:无法将类型 'UITableViewCell' 的值转换为自定义单元格类