A view of a string’s contents as a collection of UTF-16 code units.
- Xcode 6.0.1+
- Swift Standard Library
You can access a string’s view of UTF-16 code units by using its
utf16 property. A string’s UTF-16 view encodes the string’s Unicode scalar values as 16-bit integers.
Unicode scalar values that make up a string’s contents can be up to 21 bits long. The longer scalar values may need two
UInt16 values for storage. Those “pairs” of code units are called surrogate pairs.
To convert a
String instance back into a string, use the
UTF16View Elements Match NSString Characters
The UTF-16 code units of a string’s
utf16 view match the elements accessed through indexed
String does not use integer indices. If you need to access a specific position in a UTF-16 view, use Swift’s index manipulation methods. The following example accesses the fourth code unit in both the
Although the Swift overlay updates many Objective-C methods to return native Swift indices and index ranges, some still return instances of
NSRange. To convert an
NSRange instance to a range of
String, use the
Range(_: initializer, which takes an
NSRange and a string as arguments.