How to get the length of a String in Swift

There is no method named ‘length’


As soon as Swift was announced, I read the few page primer and immediately began programming. No, I didn’t read the entire book cover to cover, but I’m well on my way there at this point in time. One piece of information that I immediately wanted to know was how I should go about calculating the length/size of a String.

In Objective-C, it was as easy as:

NSString *string = @“Test”;
int length = string.length; // = 4

Apple explicitly states in their Swift iBook that the String class is bridged seamlessly to the NSString class and can make use of its APIs, however, the length method doesn’t exist. That’s because unicode characters in Swift don’t all take up the same unit of storage in memory, and therefore calling NSString’s length , which is based on 16-bit code units, on a Swift String, wont work. However, Apple had enough sense to foresee this as an issue for developers and bridged the functionality of NSString’s length method to a method named utf16count.

In Swift, to calculate the length of a String object, one must do the following:

let string = “test” // or 'var string' if you want a variable
let len = string.utf16count // = 4
let objcLen = string.bridgeToObjectiveC().length// = 4

where the bridgeToObjectiveC() function allows you to directly call length on your Swift String. However, that involves more typing, so stick with the utf16count method.

Email me when Arthur’s Coding Tips publishes stories