Skip to content

Instantly share code, notes, and snippets.

@riteshhgupta
Created December 12, 2016 18:16
Show Gist options
  • Save riteshhgupta/cfcd8119c8309ca60682fa338ac49fac to your computer and use it in GitHub Desktop.
Save riteshhgupta/cfcd8119c8309ca60682fa338ac49fac to your computer and use it in GitHub Desktop.
public extension Collection where Iterator.Element: Equatable {
public func after(_ element: Iterator.Element) -> Iterator.Element? {
guard let idx = index(of: element), index(after: idx) < endIndex else { return nil }
let nextIdx = index(after: idx)
return self[nextIdx]
}
public func before(_ element: Iterator.Element) -> Iterator.Element? {
guard let idx = index(of: element), index(before: idx) >= startIndex else { return nil }
let previousIdx = index(idx, offsetBy: -1)
return self[previousIdx]
}
public func index(before idx: Index) -> Index {
return index(idx, offsetBy: -1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment