Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift : Generic parameter 'T' could not be inferred

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.

like image 883
Denis Avatar asked Dec 10 '22 04:12

Denis


1 Answers

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.

like image 158
eirikvaa Avatar answered Jan 14 '23 08:01

eirikvaa