Created
October 5, 2017 07:03
-
-
Save cemolcay/88d95b679d54316edc0bb8f6445ba73d to your computer and use it in GitHub Desktop.
Swift circular array subscript
This file contains 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 { | |
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
commented
Apr 27, 2020
My attempt:
- Handles a negative index so you can go circular in either direction.
- 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