I want to learn the best/simplest way to turn a string into another string but with only a subset, starting at the beginning and going to the last index of a character.
The one thing that adds clatter is the repeated stringVar:
stringVar[stringVar.index(stringVar.startIndex, offsetBy: ...)
In Swift 4
An extension can reduce some of that:
extension String {
func index(at location: Int) -> String.Index {
return self.index(self.startIndex, offsetBy: location)
}
}
Then, usage:
let string = "abcde"
let to = string[..
It should be noted that to and from are type Substring (or String.SubSequance). They do not allocate new strings and are more efficient for processing.
To get back a String type, Substring needs to be casted back to String:
let backToString = String(from)
This is where a string is finally allocated.