Skip to content

Instantly share code, notes, and snippets.

@klein-artur
Created October 24, 2016 11:32
Show Gist options
  • Save klein-artur/de85528b34777b4d433df28a76ced9b0 to your computer and use it in GitHub Desktop.
Save klein-artur/de85528b34777b4d433df28a76ced9b0 to your computer and use it in GitHub Desktop.
String extension to get a substring by UInt indexes.
extension String {
func substring(from: UInt, length: UInt) -> String {
if Int(from) >= self.characters.count {
preconditionFailure("from is out of bounds.")
}
if Int(from+length) > self.characters.count {
preconditionFailure("from and lenght are out of bounds")
}
let startIndex = self.index(self.startIndex, offsetBy: String.IndexDistance(from))
let endIndex = self.index(self.startIndex, offsetBy: String.IndexDistance(from+length))
return self.substring(with: startIndex..<endIndex)
}
func substring(from: UInt) -> String {
if Int(from) >= self.characters.count {
preconditionFailure("from is out of bounds.")
}
let startIndex = self.index(self.startIndex, offsetBy: String.IndexDistance(from))
return self.substring(from: startIndex)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment