[swift-users] Can't implement generic subscript in protocol

Slava Pestov spestov at apple.com
Fri Sep 15 18:25:01 CDT 2017


> On Sep 15, 2017, at 12:40 PM, Joanna Carter via swift-users <swift-users at swift.org> wrote:
> 
> Greetings
> 
> Now we've got generic subscripts, I thought I'd play…
> 
> protocol DataProvider
> {
>  subscript<itemType>(index: Int) -> itemType { get }
> }

This is a valid usage of your protocol:

func doesStuff(p: DataProvider) {
  let i: Int = p[0]
  let s: String = p[1]
}

> 
> class Test : DataProvider // error : Type 'Test' does not conform to protocol 'DataProvider'
> {
>  subscript(index: Int) -> String
>  {
>    return "Fred"
>  }
> }
> 
> Simple questions:
> 
> 1. why does this not compile?

Imagine if I pass an instance of class Test to my function doesStuff() above. What would the first line of code do, given that it’s expecting to get back an Int result but the subscript in the class always returns a String?


> 2. should it?
> 3. is there a workaround without declaring an associated type in the protocol?

Either the protocol should have a non-generic subscript, or the class should have a generic subscript. Note that the same would happen if you do something like

protocol P {
  func f<T>() -> T
}

class C : P {
  func f() -> String
}

Again, here C.f is ‘too concrete’.

Slava

> 
> Joanna
> 
> --
> Joanna Carter
> Carter Consulting
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



More information about the swift-users mailing list