Skip to content

Instantly share code, notes, and snippets.

@cemolcay
Created October 5, 2017 07:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cemolcay/88d95b679d54316edc0bb8f6445ba73d to your computer and use it in GitHub Desktop.
Save cemolcay/88d95b679d54316edc0bb8f6445ba73d to your computer and use it in GitHub Desktop.
Swift circular array subscript
extension Array {
subscript(circular index: Int) -> Element? {
var i = index
if i < 0 || isEmpty {
return nil
} else if i > count - 1 {
i = index % count
}
return self[i]
}
}
@gbero
Copy link

gbero commented Apr 27, 2020

extension Array {
	subscript(circular index: Int) -> Element? {
		guard index >= 0 && !isEmpty else { return nil }
		guard index >= count else { return self[index] }
		return self[index % count]
	}
}

@matzsoft
Copy link

matzsoft commented Jul 8, 2021

My attempt:

  1. Handles a negative index so you can go circular in either direction.
  2. Has a non-optional return so that using it on an empty array will cause a fatal error like the standard subscript.
extension Array {
    subscript( circular index: Int ) -> Element {
        let modIndex = isEmpty ? 0 : index % count
        return self[ modIndex < 0 ? modIndex + count : modIndex ]
    }
}

If you prefer the optional return you can use instead:

extension Array {
    subscript( circular index: Int ) -> Element? {
        guard !isEmpty else { return nil }
        let modIndex = index % count
        return self[ modIndex < 0 ? modIndex + count : modIndex ]
    }
}

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