[swift-users] Default bounds subscript for BidirectionalCollection

Tim Vermeulen tvermeulen at me.com
Tue Jun 28 14:45:45 CDT 2016

I expected the following code to compile:

struct Wrapper<Element>: BidirectionalCollection {
    var elements: [Element]
    var startIndex: Int { return 0 }
    var endIndex: Int { return elements.count }
    func index(after index: Int) -> Int { return index + 1 }
    func index(before index: Int) -> Int { return index - 1 }
    subscript(position: Int) -> Element {
        return elements[position]

However, I got a long list of errors. I tried adding this:

extension Wrapper {
    subscript(bounds: Range<Int>) -> BidirectionalSlice<Wrapper> {
        return BidirectionalSlice(base: self, bounds: bounds)

But not Xcode shows an interesting error message: “Type `Wrapper<Element>.Index` does not conform to protocol `Comparable`”. Surely, Wrapper<Element>.Index is just Int which can be inferred from the startIndex property, for example. I tried setting the Index type explicitly:

struct Wrapper<Element>: BidirectionalCollection {
    typealias Index = Int

Now the code finally compiles. Bug?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160628/84164ad2/attachment.html>

More information about the swift-users mailing list