Created
October 12, 2017 22:04
-
-
Save natecook1000/7c066988a11f7ac70597a4404c816917 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Collection { | |
| func nth(_ n: Int) -> Element? { | |
| assert(n >= 0, "Can't get a negative-th element") | |
| guard let i = index(startIndex, offsetBy: numericCast(n), limitedBy: endIndex), | |
| i != endIndex | |
| else { return nil } | |
| return self[i] | |
| } | |
| } | |
| let str = "Hello!" | |
| str.nth(4) // "o" | |
| str.nth(6) // nil | |
| let nums = [10, 20, 30, 40] | |
| nums.nth(3) // 40 | |
| nums.nth(100) // nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment