Skip to content

Instantly share code, notes, and snippets.

@SlaunchaMan
Created June 17, 2015 18:38
Show Gist options
  • Save SlaunchaMan/369cbab0cc0df8bba321 to your computer and use it in GitHub Desktop.
Save SlaunchaMan/369cbab0cc0df8bba321 to your computer and use it in GitHub Desktop.
Getting the Next Element in a Swift Array
extension Array {
func after(item: T) -> T? {
if let index = find(self, item) where index + 1 < count {
return self[index + 1]
}
return nil
}
}
@nrbrook
Copy link

nrbrook commented Sep 2, 2021

A slightly modified version of @mvarie's solution which optionally allows wrapping back to the start or end of the collection:

extension Collection where Element: Equatable {
    
    func element(after element: Element, wrapping: Bool = false) -> Element? {
        if let index = self.firstIndex(of: element){
            let followingIndex = self.index(after: index)
            if followingIndex < self.endIndex {
                return self[followingIndex]
            } else if wrapping {
                return self[self.startIndex]
            }
        }
        return nil
    }
}

extension BidirectionalCollection where Element: Equatable {
    
    func element(before element: Element, wrapping: Bool = false) -> Element? {
        if let index = self.firstIndex(of: element){
            let precedingIndex = self.index(before: index)
            if precedingIndex >= self.startIndex {
                return self[precedingIndex]
            } else if wrapping {
                return self[self.index(before: self.endIndex)]
            }
        }
        return nil
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment