I\'m coloring some parts of a text coming from an API (think \"@mention\" as on Twitter) using NSAttributedString.
The API gives me the text and an array of entities rep
A Swift String
provides different "views" on its contents.
A good overview is given in "Strings in Swift 2" in the Swift Blog:
characters
is a collection of Character values, or extended grapheme clusters.unicodeScalars
is a collection of Unicode scalar values.utf8
is a collection of UTF–8 code units.utf16
is a collection of UTF–16 code units.As it turned out in the discussion, pos
and len
from your API
are indices into the Unicode scalars view.
On the other hand, the addAttribute()
method of NSMutableAttributedString
takes an NSRange
, i.e. the range corresponding
to indices of the UTF-16 code points in an NSString
.
String
provides methods to "translate" between indices of the
different views (compare NSRange to Range<String.Index>):
let text = "@ericd Some text.