函数在一个数组中从另一个数组中筛选相等年份的索引。
我正在寻找我的代码的更短的解决方案:
let years = (2015...2025).map { $0 }
var chosenYears = [2015, 2019, 2016] (example)这个函数可以做我想做的事情,但是我正在寻找一些东西(更多的functional-programming外观)。
func selectChoseYears() {
for (index, year) in years.enumerated() {
for chosenYear in chosenYears {
if year == chosenYear { view?.selectCell(at: index) }
}
}
}我尝试了一些解决方案,但它们看起来很难看,而且比这个还要长。
谢谢你,
发布于 2019-01-29 10:41:48
有许多可能的解决办法,例如:
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)
}发布于 2019-01-29 10:42:41
您可以直接过滤indices
years.indices.filter{ chosenYears.contains(years[$0]) }.forEach { view?.selectCell(at: $0) }我完全同意苏森的评论。不过,我将用、更高效的替换更易读、更简单的
发布于 2019-01-29 10:54:26
您可以找到具有以下函数的任何Equatable元素的索引
-一般索引查找器
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)https://stackoverflow.com/questions/54419047
复制相似问题