加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何将AnyClass转换为特定的类并在Swift中动态初始化?

发布时间:2020-12-14 06:07:03 所属栏目:百科 来源:网络整理
导读:在Object-C中,我将Class对象存储在数组中,并按如下方式动态初始化: self.controllers=@[[OneViewController class],[TwoViewController class]];Class clz = self.controllers[index];UIViewController *detailViewController = [[clz alloc] init]; 在Sw
在Object-C中,我将Class对象存储在数组中,并按如下方式动态初始化:
self.controllers=@[[OneViewController class],[TwoViewController class]];
Class clz = self.controllers[index];
UIViewController *detailViewController = [[clz alloc] init];

在Swift我尝试这种方式,但它引发一个错误:

var controllers:AnyClass[] = [OneViewController.self,TwoViewController.self]
var clz : AnyClass = controllers[index]
var instance = clz() // Error:'AnyObject' is not constructible with ()

我不知道是否有一种方法来将AnyClass转换为特定的类?
还是任何其他好的想法?

你可以指定数组为普通超类的类型,然后类型deduction做正确的事情(Beta-3语法):
let classArray: [UIViewController.Type] = [
    OneViewController.self,TwoViewController.self
]
let controllerClass = classArray[index]
let controller = controllerClass()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读