使用未申报的类型" myClass"动态创建视图控制器时

时间:2017-02-28 16:41:55

标签: swift

我希望获得一个带有类型的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 个答案:

答案 0 :(得分:1)

您在访问CollectionViewControllers之前实例化.self。因此,您不是要创建一个类数组,而是创建一个实例数组。删除()

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.")
    }
}