Skip to content

Instantly share code, notes, and snippets.

@d3signerd
Created April 4, 2018 18:25
Show Gist options
  • Save d3signerd/2ed39aefaaba4a6646bbb02910f49967 to your computer and use it in GitHub Desktop.
Save d3signerd/2ed39aefaaba4a6646bbb02910f49967 to your computer and use it in GitHub Desktop.
Swift Array next and previous Items made easier.
//
// BidirectionalCollection.swift
//
// Created by Kellen Styler
//
import Foundation
extension BidirectionalCollection where Iterator.Element: Equatable {
typealias Element = Self.Iterator.Element
func nextItem(withItem item: Element) -> Element? {
guard let itemIndex = index(of: item) else { return nil }
let nextIndex = index(after: itemIndex)
guard nextIndex != endIndex else { return nil }
return self[nextIndex]
}
func previousItem(withItem item: Element) -> Element? {
guard let itemIndex = index(of: item) else { return nil }
guard itemIndex != startIndex else { return nil }
return self[index(before: itemIndex)]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment