In a generic function, I want to test if a given object conforming to a certain protocol is of a given type. It works great if a concrete class type is passed as a parameter to the checking function. However, when I use a variable for the type (using ternary operator), I get an error:
Cannot invoke '
isObject
' with an argument list of type '(AnyObject, of: P.Type)
'
Casting additionally the type variable to P.Protocol
doesn't help either, since:
In argument type '
P.Protocol
', 'P
' does not conform to expected type 'P
'
protocol P {
static var descr: String {get}
}
class A: P {
static let descr = "class A"
}
class B: P {
static let descr = "class B"
}
class Test {
func isObject<T:P>(_ object: AnyObject, of type: T.Type) -> Bool {
print("descr: \(type.descr)")
return object is T
}
}
let a = A()
let type = (false ? A.self : B.self) as P.Type //as! P.Protocol
let test = Test()
test.isObject(a, of: type)