2017-02-28 60 views
0

我想要獲取爲類型指定的myClass值,然後從故事板實例化該值。動態創建視圖控制器時使用未聲明的類型「myClass」

func detailViewControllerClasses(index: Int) -> UIViewController { 
     let myClass = [CollectionViewController().self, CollectionViewController().self, CollectionViewController().self, CollectionViewController().self][index] 


     let storyboard = UIStoryboard(name: "Main", bundle: nil) 
     guard let vc = storyboard.instantiateViewController(withIdentifier: "CollectionViewController") as? myClass else { 
      fatalError("Unable to instatiate a ViewController from the storyboard.") 
     } 
    } 

guard let行的編譯器說: 「未聲明的變量MyClass的」。我宣佈它幾行,沒有錯誤或警告。爲什麼會發生這種錯誤?

回答

1

您在訪問.self之前實例化您的CollectionViewControllers。因此,您不是創建一個類的數組,而是一組實例。刪除()

func detailViewControllerClasses(index: Int) -> UIViewController { 
    let myClass = [CollectionViewController.self, CollectionViewController.self, CollectionViewController.self, CollectionViewController.self][index] 


    let storyboard = UIStoryboard(name: "Main", bundle: nil) 
    guard let vc = storyboard.instantiateViewController(withIdentifier: "CollectionViewController") as? myClass else { 
     fatalError("Unable to instatiate a ViewController from the storyboard.") 
    } 
}