1. Why is it illegal in Swift to write a substring expression using integers, i.e. string[1..<10]?
I understand that the length in bytes of a character varies according to the underlying character encoding, but shouldn't Swift be able to figure this out and produce the right result?
2. Why does a substring operation return a Substring object instead of a String object?
What is the use of a Substring object? In other words, in what scenario would one not immediately convert it to a String?
Both of these problems seem like a pretty big step backwards from every other language I have ever used (Objective-C, Java, C# and many others).
Thanks,
Frank
For 1.
It is easy to get an extension to do this:
extension String {
subscript (range: Range) -> String {
let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound)
let endIndex = self.index(self.startIndex, offsetBy: range.upperBound)
return String(self[startIndex..<endindex])
}
}
Credit: h ttps://edwardvalentini.com/2017/11/11/making-strings-integer-subscriptable/
2. Why does a substring operation return a Substring object instead of a String object?
What is the use of a Substring object? In other words, in what scenario would one not immediately convert it to a String?
That is clearly a design choice in Swift, that was (and is still if I understand well) discussed.
The interest of this is that you refer with the same index for the same part in String and its substring (substring is a 'screenshot window' in the String.
For both questions, this is an interesting discussion that you probably read already.
https://stackoverflow.com/questions/39677330/how-does-string-substring-work-in-swift