Skip to content

Instantly share code, notes, and snippets.

@davidsteppenbeck
Last active May 17, 2021 20:52
Show Gist options
  • Save davidsteppenbeck/a880203d6d11d7ca814ebe14ab842b32 to your computer and use it in GitHub Desktop.
Save davidsteppenbeck/a880203d6d11d7ca814ebe14ab842b32 to your computer and use it in GitHub Desktop.
Array extension method for safe index queries (Swift).
import Foundation
extension Array {
/// Safely provides the element at the requested index without encountering those dreaded index out of range errors 🥳.
///
/// Take, for example, an array of characters.
/// ````
/// let characters: [Character] = ["a", "b", "c", "d", "e"]
/// ````
/// If the provided index lies within the indices of the array, the method will return the element at that index, as normal.
/// ````
/// characters.at(0) // returns character "a"
/// characters.at(4) // returns character "e"
/// ````
/// If the provided index exceeds the maximum index of the array, the method will wrap around and start again from index `0`.
/// ````
/// characters.at(5) // returns character "a"
/// characters.at(6) // returns character "b"
/// ````
/// Similarly, if the provided index is negative, the method will wrap around but in the reverse direction.
/// ````
/// characters.at(-1) // returns character "e"
/// characters.at(-2) // returns character "d"
/// ````
///
/// - Parameters:
/// - index: The index to provide an element for.
func at(_ index: Index) -> Element {
guard indices.contains(index) else {
let overlap = index % count
if overlap < 0 {
return self[count + overlap]
} else {
return self[overlap]
}
}
return self[index]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment