Sunday, July 6, 2014

Strings in Swift

Ole Begemann:

In this article, I want to take a closer look at how strings are handled in Swift. I see this as a follow-up to a piece titled NSString and Unicode that I wrote for a while ago. Please refer to that article for a more thorough explanation of the Unicode features I mention below. I also assume that you have read the chapter on Strings and Characters in Appleʼs Swift book.


Swift strings do not have a length property. You can use the global countElements() function (which works on any Sequence, including strings) to count the number of Characters in a string. In the following example, countElements() counts the number of characters correctly whereas NSString does not. Because of the differences in what constitutes a character between String and NSString, NSStringʼs length property has been renamed utf16count when you access it on a Swift string.


Because of the way Swift strings are stored, the String type does not support random access to its Characters via an integer index — there is no direct equivalent to NSStringʼs characterAtIndex: method. Conceptually, a String can be seen as a doubly linked list of characters rather than an array.


Character and range indices are based on the opaque String.Index type, which implements the BidirectionalIndex protocol (an extension of the ForwardIndex protocol). To construct an index for a specific position, you have to first ask the string for its startIndex and then use the global advance() function to iterate over all characters between the beginning of the string and the target position (again, an O(N) operation; advance() will simply call succ() several times):


Another implication of this design is that String.Index values are not freely interchangeable between strings.

Update (2014-07-22): Ole Begemann:

I have completely rewritten my article on Strings in Swift from earlier this month. Xcode 6 beta 4 fundamentally changed how the String and Character type handle Unicode characters that are composed of multiple code points.

1 Comment

Strings in Swift seem like the place where the most work is needed. However I suspect we won't see a fleshed out string class before iOS8 is released.

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment