Created
April 4, 2018 18:25
-
-
Save d3signerd/2ed39aefaaba4a6646bbb02910f49967 to your computer and use it in GitHub Desktop.
Swift Array next and previous Items made easier.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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