Skip to content

Instantly share code, notes, and snippets.

@yonat
Created September 3, 2016 07:03
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 yonat/0a694409e0d8949929bf22daae6a7f00 to your computer and use it in GitHub Desktop.
Save yonat/0a694409e0d8949929bf22daae6a7f00 to your computer and use it in GitHub Desktop.
Perl style substring for Swift String
extension String {
/**
Perl style substring
- parameter offset: Negative offset starts that far back from the end of the string
- parameter length: Negative length leaves that many characters off the end of the string. Omit to return everything through the end of the string.
*/
func substr(offset: Int, length: Int = 0) -> String {
let start = offset < 0 ? endIndex.advancedBy(offset, limit: startIndex) : startIndex.advancedBy(offset, limit: endIndex)
let end = length > 0 ? start.advancedBy(length, limit: endIndex) : endIndex.advancedBy(length, limit: startIndex)
return substringWithRange(start ..< end)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment