Created
July 29, 2023 13:22
-
-
Save foxicode/4c9dd41ce4b5bb1b88ac01789d9c7a5a to your computer and use it in GitHub Desktop.
Easy substrings in Swift
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
| public extension String { | |
| func substring(start: Int, length: Int) -> String { | |
| if start >= count { | |
| return "" | |
| } | |
| let startIndex = index(self.startIndex, offsetBy: start) | |
| let endIndex: Index | |
| if start + length > count { | |
| endIndex = index(self.startIndex, offsetBy: count) | |
| } else { | |
| endIndex = index(self.startIndex, offsetBy: start + length) | |
| } | |
| return "\(self[startIndex..<endIndex])" | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment