Had fun making a type-safe value-oriented collection view data source in Swift today.
Conversation
I think you want countElements; it counts random-access collections in O(1) and others in O(N).
1
Oh dang! Lovely.
But what if I want to implement my own collection, for which there's a reasonable O(1) count()? :/
1
Also: how does it do this for an arbitrary CollectionType (i.e. non-Array) whose index is a RandomAccessIndexType?
1
Minor magic. I don't want to endorse it b/c we want to do better, but very close to 's nshipster.com/swift-default-
2
4
That does mean it will do the right thing if your custom collection uses RandomAccessIndexType!
1
Oh. Uh. Interesting. I don't understand: say I make my own CollectionType where Index is Int. How does countElements() count?
1
distance(collection.startIndex, collection.endIndex) → *magic* → collection.startIndex.distanceTo(collection.endIndex)
1

