alizx alizx - 7 months ago 11
Swift Question

`endIndex` and `count` of a String are different

How is it possible to

endIndex
and
count
of a
String
be different in swift2? its the code sample that I've used.it's not happen when all characters are english only.

print("count:",self.Label.text!.characters.count)
print("endIndex:",self.Label.text!.characters.endIndex)
print("String:",self.Label.text!)


output :

count: 32
endIndex: 34
String: • (دستور زبان) مفعول‌به، مفعول‌عنه

Answer

The raw value of String.CharacterView.Index is irrelevant and should not be used. Its raw value only has meaning from within String and CharacterView.

In your case, some Unicode characters are merely combining characters that modify adjacent characters to form a single grapheme. For example, U+0300, Combining Grave Accent:

    let str = "i\u{0300}o\u{0300}e\u{0300}"

    print("String:",str)
    print("count:",str.characters.count)
    print("endIndex:",str.characters.endIndex)

    var i = str.characters.startIndex
    while i < str.characters.endIndex
    {
        print("\(i):\(str.characters[i])")
        i = i.successor()
    }

results in

String: ìòè
count: 3
endIndex: 6
0:ì
2:ò
4:è