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] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My attempt:
If you prefer the optional return you can use instead: