Skip to content

Instantly share code, notes, and snippets.

@ElegyD
Created June 2, 2017 09:01
Show Gist options
  • Select an option

  • Save ElegyD/b1ea7b1938dcbd0804f0fb15f5073d3c to your computer and use it in GitHub Desktop.

Select an option

Save ElegyD/b1ea7b1938dcbd0804f0fb15f5073d3c to your computer and use it in GitHub Desktop.
Swift 3 String substring extension for easier handling if offset exceeds endIndex
extension String {
/// Returns a new string containing the characters of the String from the one at a given index to the end. If 'from' exceeds endIndex it returns an empty string.
func substring(from: Int) -> String {
guard let offsetStartIndex = index(startIndex, offsetBy: from, limitedBy: endIndex) else { return "" }
return self[offsetStartIndex..<endIndex]
}
/// Returns a new string containing the characters of the String up to the one at a given index. If 'to' exceeds endIndex it returns the string as it was.
func substring(to: Int) -> String {
return self[startIndex..<(index(startIndex, offsetBy: to, limitedBy: endIndex) ?? endIndex)]
}
/// Returns a string object containing the characters of the String that lie within a given range. If 'from' exceeds endIndex it returns an empty string. If 'to' exceeds endIndex it returns the string from 'from' to endIndex.
func substring(from: Int, to: Int) -> String {
guard let offsetStartIndex = index(startIndex, offsetBy: from, limitedBy: endIndex) else { return "" }
guard let offsetEndIndex = index(startIndex, offsetBy: to, limitedBy: endIndex) else { return self[offsetStartIndex..<endIndex] }
return self[offsetStartIndex..<offsetEndIndex]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment