我带着这个简单的游乐场来说明我的问题:
import UIKit
protocol MyProtocol {
var foo: Bool { get set }
}
class MyGenericClass<T: UIView where T: MyProtocol>: UIView {}
func checkIfIsMyGenericClass(view: UIView) -> Bool {
return view is MyGenericClass // Generic parameter 'T' could not be inferred
}
我需要帮助来识别MyGenericClass
。
我的实际代码并不那么简单,请不要让我更改MyGenericClass
声明。
答案 0 :(得分:0)
MyGenericClass具有associatedType要求。我不确定,但你可以试试像
这样的东西import UIKit
protocol MyProtocol {
var foo: Bool { get set }
}
class MyGenericClass<T: UIView where T: MyProtocol>: UIView {}
func checkIfIsMyGenericClass<T: UIView where T: MyProtocol>(view: T) -> Bool {
return view is MyGenericClass<T> // Generic parameter 'T' could not be inferred
}
<强>已更新强>
import UIKit
protocol MyProtocol {
var foo: Bool { get set }
}
class View: UIView, MyProtocol {
var foo: Bool = true
}
class MyGenericClass<T: UIView where T: MyProtocol>: UIView {
var variable: T!
init() {
super.init(frame: CGRectZero)
}
}
let view = View()
let obj = MyGenericClass<View>()
obj.variable = view
let anyOtherObj = UIView()
func checkIfIsMyGenericClass<T: UIView where T: MyProtocol>(view: UIView, type: T) -> Bool {
return view is MyGenericClass<T>
}
checkIfIsMyGenericClass(obj, type: view) // returns true
checkIfIsMyGenericClass(anyOtherObj, type: view) // returns false