我带着这个简单的游乐场来说明我的问题:
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
声明。 最佳答案
MyGenericClass具有关联的类型要求。我不确定,但你能不能试试
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