2017-01-16 105 views
0
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' 
+0

我莫名其妙地成功斯威夫特編譯這3 – Sweeper

回答

0

就不得不強制轉換爲:any.Type

let passedType = ofType as? Any.Type 
if classType == passedType { 
    print("there is a match") 
} 
1

當您需要調用泛型的參數名稱時,您只需調用泛型。

你試過:

if classType == ofType.self { ... 
+0

啊,沒錯只是去嘗試仍然得到錯誤:二元運算符「==」不能應用於類型「Any.Type」和「T」的操作數 –

0

斯威夫特3 isKindOf只是is所以你應該使用類似:

if classType is SecondViewController { 
    print("there is a match") 
} 
0

我認爲應該使用=== 蘋果迅速的編程語言,p.768