我有一个名为openApp的类,这意味着要使用重定向URL和存储工具包打开另一个应用程序。我对泛型不太熟悉,这让我遇到了这个错误
无法推断出通用参数'T'
我不能正确处理T
的使用吗?我真的不明白这里发生了什么。
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)
}
}
}
答案 0 :(得分:3)
由于问题是在调用 openOrDownloadPlayPortal
方法时出现:
openApp.openOrDownloadPlayPortal(delegate: self)
您将遇到上述错误:
无法推断出通用参数'T'
如果您的班级不符合SKStoreProductViewControllerDelegate
。例如,假设您正在ViewController
类中调用它,如下所示:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
openApp.openOrDownloadPlayPortal(delegate: self)
}
}
因此,您必须确保ViewController
具有:
extension ViewController: SKStoreProductViewControllerDelegate {
// ...
}
错误的原因是:编译器假定T
方法中的openOrDownloadPlayPortal
参数必须符合SKStoreProductViewControllerDelegate
,因此实现
openApp.openOrDownloadPlayPortal(delegate: self)
意味着除非您使T
(在上面的示例中为self
)与ViewController
兼容,否则它将不会被认为是SKStoreProductViewControllerDelegate
的适当类型。