Skip to content

Instantly share code, notes, and snippets.

@NeilsUltimateLab
Created May 12, 2018 11:23
Show Gist options
  • Save NeilsUltimateLab/9b402f235c36fc2428c74ddfc7db248b to your computer and use it in GitHub Desktop.
Save NeilsUltimateLab/9b402f235c36fc2428c74ddfc7db248b to your computer and use it in GitHub Desktop.
Generate IndexPaths from Sectioned DataSource
protocol SectionProviderProtocol {
associatedtype T
var header: String? { get }
var rows: [T] { get }
}
extension Array where Element: SectionProviderProtocol, Element.T: Equatable {
var indexPaths: [IndexPath] {
var paths: [IndexPath] = []
for (section, item) in self.enumerated() {
let ips = (0..<item.rows.count).map({IndexPath(row: $0, section: section)})
paths.append(contentsOf: ips)
}
return paths
}
func indexPaths<T>(from another: Array<T>) -> [IndexPath] where T == Element.T {
var paths = [IndexPath]()
for (section, item) in self.enumerated() {
if let index = item.rows.indices(from: another) {
let idx = index.compactMap({IndexPath(row: $0, section: section)})
paths.append(contentsOf: idx)
}
}
return paths
}
}
extension Array where Element: Equatable {
func indices(from another: Array) -> [Int]? {
guard !another.isEmpty else { return nil }
var idx: [Int] = []
for element in another {
if let index = self.index(of: element) {
idx.append(index)
}
}
return idx.isEmpty ? nil : idx
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment