![](/img/trans.png)
[英]Cannot convert a viewController object to viewController type in Swift
[英]Comparing ViewController to a type in swift
extension UIViewController {
func getChildViewController<T>(OfType: T) {
let classType = Mirror(reflecting: self.childViewControllers.first).subjectType
if classType == T.self {
print("there is a match")
}
}
}
這是UIViewController的擴展,當您調用此函數時,可以將其傳遞為一種類型,例如:
ViewController.getChildViewController(OfType: SecondViewController.self)
這將檢查視圖控制器的第一個孩子是否類型為SecondViewController
但是在if語句中,我得到了錯誤:
Binary operator '==' cannot be applied to operands of type 'Any.Type' and 'T'
Swift 3中的isKindOf
只是is
所以您應該使用類似以下內容的代碼:
if classType is SecondViewController {
print("there is a match")
}
當您需要調用泛型的參數名稱時,您只是在調用泛型。
你有沒有嘗試過:
if classType == ofType.self { ...
我認為應該使用=== Apple Swift編程語言p.768
只需將其強制轉換為:any.Type
let passedType = ofType as? Any.Type
if classType == passedType {
print("there is a match")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.