在通用函數中,我想測試符合特定協議的給定對象是否爲給定類型。如果具體的類類型作爲參數傳遞給檢查函數,它會很好用。然而,當我使用一個變量的類型(使用三元運算符),我得到一個錯誤:使用符合協議的類型變量調用通用函數
Cannot invoke '
isObject
' with an argument list of type '(AnyObject, of: P.Type)
'
鑄造另外的類型變量P.Protocol
並沒有幫助,因爲:
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)