I appreciate this question and all the info with it. I have something in mind that's kind of a question and an answer when it comes to String.Index.
I'm trying to see if there is an O(1) way to access a Substring (or Character) inside a String because string.index(startIndex, offsetBy: 1) is O(n) speed if you look at the definition of index function. Of course we can do something like:
let characterArray = Array(string)
then access any position in the characterArray however SPACE complexity of this is n
= length of string, O(n) so it's kind of a waste of space.
I was looking at Swift.String documentation in Xcode and there is a frozen public struct called Index
. We can initialize is as:
let index = String.Index(encodedOffset: 0)
Then simply access or print any index in our String object as such:
print(string[index])
Note: be careful not to go out of bounds`
This works and that's great but what is the run-time and space complexity of doing it this way? Is it any better?