一般的な関数では、特定のプロトコルに準拠する特定のオブジェクトが所定の型であるかどうかをテストします。具体的なクラス型がチェック関数のパラメータとして渡された場合にはうまくいきます。私は(三項演算子を使用して)タイプの変数を使用する場合しかし、私はエラーを取得する:P.Protocol
に加えて型変数キャスティングプロトコルに準拠した型変数を持つ汎用関数を呼び出す
Cannot invoke '
isObject
' with an argument list of type '(AnyObject, of: P.Type)
'
は、いずれかの助けにはならない、以来:
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)