Arrays 查找索引的简短解决方案

Arrays 查找索引的简短解决方案,arrays,swift,Arrays,Swift,函数是从一个数组中从另一个数组中筛选出相同年份的索引 我正在寻找代码的较短解决方案: let years = (2015...2025).map { $0 } var chosenYears = [2015, 2019, 2016] (example) 这个函数实现了我想要的功能,但我正在寻找一些东西(更多函数编程look) 我尝试了一些解决方案,但它们看起来很难看,而且比这还要长 谢谢。试试: let result = (2015...2025).map { $0 }.filter {

函数是从一个数组中从另一个数组中筛选出相同年份的索引

我正在寻找代码的较短解决方案:

 let years = (2015...2025).map { $0 }
 var chosenYears = [2015, 2019, 2016] (example)
这个函数实现了我想要的功能,但我正在寻找一些东西(更多
函数编程
look)

我尝试了一些解决方案,但它们看起来很难看,而且比这还要长

谢谢。试试:

let result = (2015...2025).map { $0 }.filter { [2015, 2019, 2016].contains($0)}

有许多可能的解决方案,例如:

let yearIndices = chosenYears.compactMap { years.index(of: $0) }
for yearIndex in yearIndices {
   view?.selectCell(at: yearIndex)
}
或者只是

for (index, year) in years.enumerated() where chosenYears.contains(year) {
    view?.selectCell(at: index)
}

您可以尝试以下方法:

self.tableView.visibleCells
.flatMap { $0 as? MyCell }
.forEach { $0.updateView(isSelected: chosenYears.contains($0.viewModel?.year) }

虽然它要求单元格存储视图模型及其表示的年份,并且您需要实现updateView(isSelected:)

但您可以直接过滤
索引

years.indices.filter{ chosenYears.contains(years[$0]) }.forEach { view?.selectCell(at: $0) }

我完全同意苏丹的评论。但是,我会用更高效的替换更可读、更简单的

您可以使用以下函数找到任何
可平等的
元素的索引

-通用索引查找器
在编程中寻找“更短”是第一个错误。你应该总是寻找“更可读”或“更简单”,而不是“更短”。@Sulthan是对的。当涉及到集合和枚举时,你也应该考虑“效率”。您的意思是
[201520192016]。包含($0)
?顺便说一句,无需调用
范围上的
映射
来将其转换为
数组
数组(2015…2025)
工作正常。为什么需要
可比
包含()
需要比较元素。但你又是对的。用更好的选择编辑。;)很好的解决方案。谢谢此外,还可以考虑编写<代码> CHOSN年份 A<代码> SET>代码>而不是数组。这将使第二个解决方案更加有效。谢谢。我也喜欢这个解决方案!
years.indices.filter{ chosenYears.contains(years[$0]) }.forEach { view?.selectCell(at: $0) }
func indexes<T: Equatable>(of chosen: [T], in all: [T]) -> [Int] {
    return all.enumerated().filter { chosen.contains($0.element) }.map { $0.offset }
}
indexes(of: chosenYears, in: years)