我希望获得一个带有类型的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"。我宣布它几行,没有错误或警告。为什么会发生这种错误?
答案 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.")
}
}