Created
June 17, 2015 18:38
-
-
Save SlaunchaMan/369cbab0cc0df8bba321 to your computer and use it in GitHub Desktop.
Getting the Next Element in a Swift Array
This file contains hidden or 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
extension Array { | |
func after(item: T) -> T? { | |
if let index = find(self, item) where index + 1 < count { | |
return self[index + 1] | |
} | |
return nil | |
} | |
} |
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
Another version, to get the preceding or following element of an Array (Collection), if any.
This version makes no assumptions about the nature of the index (it is not assumed that the index is an
Int
, nor it is assumed that the index is contiguous). Rather,index(after: index)
andindex(before: index)
are used to determine the preceding/following index.For forward lookups, the extension is applied to
Collection
, while for backwards lookups, it is applied toBidirectionalCollection
: so that these functions can be used on any collection that supports the construct, not just theArray
type.These functions are not circular (asking for the element that follows the last element in an Array will return
nil
, not the first element).As with any other solution offered on this page, it is assumed that the array has no duplicates. E.g., if your array is
[A, B, C, B, E]
and you're asking for the element that followsB
, you will always getC
.