2 Big Swift String Changes
While converting an open source project over to the latest version of Swift, I ran into some interesting details regarding the String type. Before I begin, this is what it looks like to convert a project to the newest Swift syntax:
The first big change in the new String type is that you no longer have a length property. If you want the "length" of a string, you use: myString.characters.count. You can get around this by casting to NSString; however, there is a pitfall to look out for:
“The length of an NSString is based on the number of 16-bit code units within the string’s UTF-16 representation and not the number of Unicode extended grapheme clusters within the string.”
Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2.2 Prerelease).” iBooks. https://itun.es/us/k5SW7.l
As you can see, the values of certain characters in length, are not 1. This could cause some interesting problems depending on what you're parsing. A quick side note: myString.bridgeToObjectiveC().length does not seem to work anymore. I've seen examples of this function being used in place of a cast.
The second big change is that you can't index into Swift strings with integers. Strings use an index value that is actually a struct. So now you have to create an index and advance it when iterating over a string like this for example:
Or better yet, use the indices property like this:
I'm in the process of diving deep into strings because the need to process and manipulate them when working with the web, is high. This piece is probably the beginning of a long and in depth blog post. Powerful coding!