Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Created October 12, 2017 22:04
Show Gist options
  • Select an option

  • Save natecook1000/7c066988a11f7ac70597a4404c816917 to your computer and use it in GitHub Desktop.

Select an option

Save natecook1000/7c066988a11f7ac70597a4404c816917 to your computer and use it in GitHub Desktop.
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