4

I have a protocol called P, and I want to write a function that would return an instance of any type conforming to that protocol.

I wrote this:

func f<T: P>() -> T? {
    // ... 
}

But then when I try to call it:

var fp = f()

I get this error: Generic parameter 'T' could not be inferred. What am I doing wrong and how to solve this? Thanks for your help.

Denis
  • 169
  • 2
  • 3
  • 9
  • 3
    What type `fp` supposed to be? Even I, human, cannot infer it. – user28434'mstep Jan 17 '19 at 16:28
  • Maybe could be helpful: [Generics in Swift - "Generic parameter 'T' could not be inferred](https://stackoverflow.com/questions/38999102/generics-in-swift-generic-parameter-t-could-not-be-inferred) – Robert Dresler Jan 17 '19 at 16:36

1 Answers1

15

You're very close. Say you have a struct A that conforms to P. Then you could specify the generic parameter as follows:

var fp: A? = f()

Without that information, the compiler can't know what type fp should be.

jscs
  • 63,694
  • 13
  • 151
  • 195
eirikvaa
  • 1,070
  • 1
  • 13
  • 24
  • Hi and thank you! Well, I'm beginning to understand, but still I have another question: what if I have, say, two structs `S1` and `S2`, each conforming to `P`, and want to create a function that could return either an instance of `S1` or of `S2`? With classes I would have created a `C` class conforming to `S`, and then the two sub-types would inherit `C`, but here I'm stuck with structs. – Denis Jan 17 '19 at 16:41
  • You can return either `S1` or `S2` from that function as long as they conform to `P`, that's no problem at all. You don't need to specify that the return type is a union of `S1` and `S2` (actually you can't directly do that in Swift right now). Do you _only_ want to return either of those two? – eirikvaa Jan 17 '19 at 16:47
  • Well actually it's just an example, I could for sure want to return any struct conforming to `P` and there could be 10 different ones... – Denis Jan 17 '19 at 16:52
  • Yes, I understood that, but why aren't your problem solved with the code you've shown and my solution? I can return any type I want that conforms to `P`. – eirikvaa Jan 17 '19 at 17:17
  • It is actually. Thank you for your answers! – Denis Jan 18 '19 at 10:02