Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.


That pesky String.Index

I don't know about you, but I keep getting "interesting" behaviour when using String.Index. All in all, iterating over strings using the String.Index has gotten a whole lot more difficult in Swift as opposed to Obj-C.

Don't take me wrong, I actually like the String.Index, it forces me to really think about what I want and make sure that the Data Model and GUI code are as separated as they should be.

Still... :-)

Take this example: I have to iterate over a string, incrementally forming ever larger substrings starting from the one-character substring up the the complete length of the original string.

I.e, given the string "Swift" the first substring would be "S", the second "Sw" and so on up to the last one which would be "Swift".

The first thought is:

let str = "Swift"

for i in str.startIndex.successor() ... str.endIndex {
    let substr = str.substringToIndex(i)


But that won't work. You will get the error "cannot increment str.endIndex" at runtime. Even though str.substringToIndex(str.endIndex) will actually work.

I tried rewriting this in several ways, but it seems that no loop construct can properly handle this case. You will need to roll your own:

let str = "Swift"

var i = str.startIndex.successor()
while true {
    let substr = str.substringToIndex(i)
    if i < str.endIndex { i = i.successor() } else { break }

Oh well...

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment