M. Mayer M. Mayer - 2 months ago 10
Swift Question

In Swift, is the count of an instance of String.CharacterView always equal to the distance between the startIndex and endIndex in all cases?

The title says it all. In Swift, is the count of an instance of String.CharacterView always equal to the distance between the startIndex and endIndex in all cases?

Swift 2.3:

string.characters.count == string.characters.startIndex.distanceTo(string.characters.endIndex)

Swift 3:

string.characters.count == string.characters.distance(from:string.characters.startIndex, to:string.characters.endIndex)

Answer

Yes. This is a requirement of Collection. It is mandatory that iterating from startIndex to endIndex exactly cover all the elements. The number of steps that would take (the distance) must be equivalent to count or you would violate that requirement.