1

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: • (دستور زبان) مفعول‌به، مفعول‌عنه
1
  • what about swift 3? Commented Jun 26, 2017 at 19:32

1 Answer 1

5

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:è
Sign up to request clarification or add additional context in comments.

5 Comments

do you know how can I get order of character? I mean getting 2 for index of 4 in your example è
Use distanceTo() to get the number of characters between two indexes. startIndex.distanceTo(i) returns to "2" for index "4". Use advanceBy() to increment an index by a number of characters.
I have an integer form layoutManager.characterIndexForPoint(...) I don't know how to convert it to Sting.Index type
startIndex.advancyBy(number)
this Int is 4 for è not the 2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.