Swift - String vs NSString

Introduction

To deal with special characters such as emoji or Chinese characters that take up two or three bytes, use the native String type in Swift.

For example, consider the following statement:

let bouquet = "\u{1F490}"

Here, bouquet contains a single emoji.

It occupies two bytes of storage.

To count the number of characters contained within the string, the countElements() method counts it correctly:

print(countElements("\(bouquet)"))   //1

If you use the NSString 's length property, it returns the storage required instead of the number of characters contained within the string:

print((bouquet as NSString).length)  //2

If you append the COMBINING GRAVE ACCENT scalar to a string, the countElements() method will count the characters correctly, whereas the length property does not:

Demo

var s6 = "voila" + "\u{300}"      
print(countElements(s6))         //5
print((s6 as NSString).length)   //6

Using the native String type enables you to use the various string features:

  • string concatenation using the + operator
  • the For-In loop for character iteration,
  • etc.

Once you explicitly declare a variable as NSString , you lose all these features.

To have the best of both, create a native String instance and then typecast to NSString to call the NSString 's methods whenever necessary.

Related Topic