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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With