Cannot use subscript

This code

enum ComparableIndexingHelper {
    case biggest
    case smallest
}
protocol CustomIndexable where Self: Collection {
    subscript (_ someIndexable: ComparableIndexingHelper) -> SortingResult<Self> { get }
}
enum SortingResult<Seq: Collection> {
    case slice(Slice<Seq>)
    case singleItem(Seq.Element)
    case nothing
}
extension CustomIndexable where Self: RangeReplaceableCollection, Self.Element: Comparable {
    subscript (_ someIndexer: ComparableIndexingHelper) -> SortingResult<Self> {
        ...
    }
}

print([1,2,2,3,3,3][ComparableIndexingHelper.biggest])
print([1,2,2,3,3,3][.biggest])

outputs this

error: no exact matches in a call to subscript

Bug or not? :woman_facepalming:

That code snippet does not conform any types to your protocol.

1 Like

To expand what @Nevin said, there's generally no notion of automatic conformance in Swift*. A type does not conform to a protocol simply by satisfying requirements, it needs to express that it conforms to it.

In this case, Array won't conform to CustomIndexable only by being a RangeReplaceableCollection with Comparable elements. Array also needs to express that it conforms to CustomIndexable.

extension Array: CustomIndexable where Element: Comparable { ... }

* One of a few exceptions is that simple enums are Hashable by default.

5 Likes