Skip to content

Instantly share code, notes, and snippets.

@cemolcay
Created October 8, 2018 01:52
Show Gist options
  • Save cemolcay/e5aa0952018df09c824467035640697e to your computer and use it in GitHub Desktop.
Save cemolcay/e5aa0952018df09c824467035640697e to your computer and use it in GitHub Desktop.
An array subscript extension that returns the element from the positive or negative circular index.
import Foundation
extension Array {
/// An array subscript extension that returns the element from the positive or negative circular index.
public subscript(circular index: Int) -> Element? {
guard count > 0 else { return nil }
let mod = index % count
let offset = index >= 0 ? 0 : count
let idx = mod == 0 ? 0 : mod + offset
return self[idx]
}
}
// Examples
let a = [0, 1, 2, 3, 4, 5]
a[circular: 0] // 0
a[circular: 1] // 1
a[circular: 2] // 2
a[circular: 3] // 3
a[circular: 4] // 4
a[circular: 5] // 5
a[circular: 6] // 0
a[circular: 7] // 1
a[circular: 8] // 2
a[circular: 12] // 0
a[circular: -1] // 5
a[circular: -2] // 4
a[circular: -3] // 3
a[circular: -4] // 2
a[circular: -5] // 1
a[circular: -6] // 0
a[circular: -7] // 5
a[circular: -12] // 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment