Created
September 3, 2016 07:03
-
-
Save yonat/0a694409e0d8949929bf22daae6a7f00 to your computer and use it in GitHub Desktop.
Perl style substring for Swift String
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 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