[swift-dev] Type inference failing to solve Collection's associated types in protocol extensions

Dimitri Racordon Dimitri.Racordon at unige.ch
Mon Sep 4 05:41:05 CDT 2017


Hello fellow Swift enthusiasts.

I’m struggling to understand why type inference fails to solve Collection s associated types while trying to provide it with a default implementation, via protocol extensions, when an additional subscript is provided. Here is a minimal example:

protocol SearchTree: Collection {
    subscript(key: Int) -> String? { get }
}

extension SearchTree {
    // MARK: Conformance to Sequence
    func makeIterator() -> AnyIterator<(key: Int, value: String)> {
        return AnyIterator { nil }
    }

    // MARK: Conformance to Collection
    var startIndex: Int { return 0 }
    var endIndex: Int { return 0 }
    func index(after i: Int) -> Int { return 0 }
    subscript(key: Int) -> (key: Int, value: String) { return (0, "") }

    // MARK: Conformance to SearchTree
    subscript(key: Int) -> String? { return nil }
}

struct ConformingTree: SearchTree {
}

Swift’s compiler complains that ConformingTree doesn’t conform to Collection. But it doesn’t say a word if I either remove the additional subscript `(key: Int) -> String?`, or if I push the declaration of the subscript in ConformingTree.

I asked this question on StackOverflow (https://stackoverflow.com/questions/46028205), and was kindly taught that I should specify associated types in the protocol (or in the extension via type aliases) because the type inference was getting confused determining the type of Collection.Element, having to deal with two subscripts. What I still don’t understand is why the type inference doesn’t need such explicit additional information when the implementation of SearchTree’s requirement is placed in the concrete type.

Could anyone enlighten me on this?

Thanks a lot for your time.
Best regards.

Dimitri Racordon
CUI, Université de Genève
7, route de Drize, CH-1227 Carouge - Switzerland
Phone: +41 22 379 01 24




-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-dev/attachments/20170904/4fe64eab/attachment.html>


More information about the swift-dev mailing list