swift - 动态创建 View Controller 时使用未声明的类型 "myClass"

标签 swift

我想获得一个分配有类型的 myClass 值,然后从 Storyboard 中实例化它。

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”。我宣布它有几行没有错误或警告。为什么会出现此错误?

最佳答案

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

关于swift - 动态创建 View Controller 时使用未声明的类型 "myClass",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42514250/

相关文章:

objective-c - 升级到 Xcode 7.3 swift 2.2 后,从 swift 调用 obj-c 枚举不起作用

ios - 使用 iOS 发送大量短信

swift - 为 MPMediaItemArtwork 声明变量(init() 不可用)

ios - 如何在 Swift 中从我的应用程序打开 iphone 应用程序?

arrays - 在 tableview 的 as 部分按日期过滤数组

xcode - 在 Swift 中禁用应用程序小睡

使用 UIDocumentInteractionController 时,Swift 崩溃 wen 敲击 “Open in Instagram”

ios - 赋予它们所有可选值

ios - 我使用此代码弹出一个带有“取消”和“提交”选项的文本字段,但键盘也显示。我不想显示键盘

swift - 电池电量不足会停止定位服务还是无法获取位置?