Skip to content

Instantly share code, notes, and snippets.

@foxicode
Created July 29, 2023 13:22
Show Gist options
  • Select an option

  • Save foxicode/4c9dd41ce4b5bb1b88ac01789d9c7a5a to your computer and use it in GitHub Desktop.

Select an option

Save foxicode/4c9dd41ce4b5bb1b88ac01789d9c7a5a to your computer and use it in GitHub Desktop.
Easy substrings in Swift
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