Reputation: 1770
Function is filtered indexes of equal years in one array from another.
I'm looking for shorter solution of my code:
let years = (2015...2025).map { $0 }
var chosenYears = [2015, 2019, 2016] (example)
This function does what i want, but i'm looking for something (more functional-programming
look).
func selectChoseYears() {
for (index, year) in years.enumerated() {
for chosenYear in chosenYears {
if year == chosenYear { view?.selectCell(at: index) }
}
}
}
I tried some solutions, but they look ugly and longer than this.
Thank you.
Upvotes: 0
Views: 110
Reputation: 5588
try :
let result = (2015...2025).map { $0 }.filter { [2015, 2019, 2016].contains($0)}
Upvotes: 0
Reputation: 119302
You can find indexes of any Equatable
elements with the following function
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)
Upvotes: 1
Reputation: 285079
You can filter the indices
directly
years.indices.filter{ chosenYears.contains(years[$0]) }.forEach { view?.selectCell(at: $0) }
I totally agree with Sulthan's comment. However I would replace more readable and simpler with more efficient
Upvotes: 2
Reputation: 29
You might try something like this:
self.tableView.visibleCells
.flatMap { $0 as? MyCell }
.forEach { $0.updateView(isSelected: chosenYears.contains($0.viewModel?.year) }
Although it requires that the cells store view model with the year it represents and you need to implement updateView(isSelected:)
Upvotes: 0
Reputation: 130102
There are many possible solutions, for example:
let yearIndices = chosenYears.compactMap { years.index(of: $0) }
for yearIndex in yearIndices {
view?.selectCell(at: yearIndex)
}
or just
for (index, year) in years.enumerated() where chosenYears.contains(year) {
view?.selectCell(at: index)
}
Upvotes: 4