Strings in Swift
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 objc.io 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 globalcountElements()
function (which works on anySequence
, including strings) to count the number ofCharacter
s in a string. In the following example,countElements()
counts the number of characters correctly whereasNSString
does not. Because of the differences in what constitutes a character betweenString
andNSString
,NSString
ʼslength
property has been renamedutf16count
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 itsCharacter
s via an integer index — there is no direct equivalent toNSString
ʼscharacterAtIndex:
method. Conceptually, aString
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 theBidirectionalIndex
protocol (an extension of theForwardIndex
protocol). To construct an index for a specific position, you have to first ask the string for itsstartIndex
and then use the globaladvance()
function to iterate over all characters between the beginning of the string and the target position (again, an O(N) operation;advance()
will simply callsucc()
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
andCharacter
type handle Unicode characters that are composed of multiple code points.
1 Comment RSS · Twitter
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.