Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Last active April 15, 2022 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krzyzanowskim/a289ea3ad1afadba45a942b06dcb2a9f to your computer and use it in GitHub Desktop.
Save krzyzanowskim/a289ea3ad1afadba45a942b06dcb2a9f to your computer and use it in GitHub Desktop.
Stride String
extension String {
func stride(by distance: String.IndexDistance, substring: (String.SubSequence) -> Void) {
guard distance > 0, distance < count else {
substring(self[...])
return
}
var i = index(startIndex, offsetBy: distance, limitedBy: endIndex) ?? endIndex
var previ = startIndex
while i < endIndex {
substring(self[previ..<i])
previ = i
i = index(i, offsetBy: distance, limitedBy: endIndex) ?? endIndex
}
substring(self[previ..<i])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment