Search code examples
iosswiftgenericsstorekit

Generic Paramter 'T' could not be inferred - Problems with generics


I have this class called openApp, thats meant to open another app using a redirect url and store kit. Im not too familiar with generics and its making me run into this error

Generic Parameter 'T' could not be inferred

Am I not handling the use of T correctly? I really don't understand whats going on here.

public class openApp {
        static func openOrDownloadPlayPortal<T>(delegate: T) where T: SKStoreProductViewControllerDelegate, T:
            UIViewController {

            let storeProductVC = SKStoreProductViewController()
            let playPortalURL = URL(string: "redirect url")!


            if UIApplication.shared.canOpenURL(playPortalURL) {
                UIApplication.shared.openURL(playPortalURL)
            }
            else {
                let vc = SKStoreProductViewController()
                let params = [
                    SKStoreProductParameterITunesItemIdentifier: "app identifier"
                ]
                vc.loadProduct(withParameters: params) { success, err in
                    if let err = err {

                    }
                }
                vc.delegate = delegate
                delegate.present(vc, animated: true, completion: nil)
            }
        }
    }

Solution

  • Since the issue appears when calling the openOrDownloadPlayPortal method as:

    openApp.openOrDownloadPlayPortal(delegate: self)
    

    You will face the mentioned error:

    Generic parameter 'T' could not be inferred

    if your class does not conforms to the SKStoreProductViewControllerDelegate. For example, let's assume that you are calling it in ViewController class, as:

    class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
    
            openApp.openOrDownloadPlayPortal(delegate: self)
        }
    }
    

    So, you have to make sure that ViewController has:

    extension ViewController: SKStoreProductViewControllerDelegate {
        // ...
    }
    

    The reason of the error is: the compiler assumes that the T parameter in openOrDownloadPlayPortal method has to conforms to the SKStoreProductViewControllerDelegate, therefore implementing

    openApp.openOrDownloadPlayPortal(delegate: self)
    

    means that it will not be recognized as the appropriate type for the T, unless you make self (ViewController in the above example) to be conformable to SKStoreProductViewControllerDelegate.