Swift.String.Index is calculated with UTF-16 not UnicodeScalar?

471 Views Asked by At

I thought String.Index is calculated with UnicodeScalar. but, When I checked endIndex of string contains one emoji only, Index is looks like UTF-16 position.

let string = "a"
string.utf16.count // 1
string.unicodeScalars.count // 1
print(string.endIndex)
// > Index(_base: Swift.String.UnicodeScalarView.Index(_position: 1), _countUTF16: 0)
// 

let emoji = ""
emoji.utf16.count // 2
emoji.unicodeScalars.count // 1

print(emoji.endIndex)
// > Index(_base: Swift.String.UnicodeScalarView.Index(_position: 2), _countUTF16: 0)
// 

Although unicodeScalar.count is 1, but position: 2. why? It's like utf16 position.

0

There are 0 best solutions below