美文网首页
AnyClass、元类型和.self

AnyClass、元类型和.self

作者: 盖小聂 | 来源:发表于2019-06-28 18:22 被阅读0次
class MusicViewController: UIViewController {
    
}

class AlbumViewController: UIViewController {
    
}

class ViewController: UIViewController {

    func setupViewControllers(vcTypes: [AnyClass]) {
        for vcType in vcTypes {
            if vcType is UIViewController.Type {
                let vc = (vcType as! UIViewController.Type).init()
                print(vc)
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //将元类型存入数组并且传递给别的方法来进行配置这一点上,元类型编程就很难被替代了。
        let usingVCTypes: [AnyClass] = [MusicViewController.self, AlbumViewController.self]
        setupViewControllers(vcTypes: usingVCTypes)
        
    }
}

补充说明:

  • typealias AnyClass = AnyObject.Type
  • 通过AnyObject.Type这种方式所得到是一个元类型(Meta)。
  • 在声明时我们总是在类型的名称后面加上.Type,比如A.Type代表的是A这个类型的类型。从A中取出其类型时,我们需要使用到.self
  • AnyClass和A.Type都是类型名称,A.self代表类型名称的值。
  • 在将这些元类型存入数组并且传递给别的方法来进行配置这一点上,元类型编程就很难被替代。

相关文章

网友评论

      本文标题:AnyClass、元类型和.self

      本文链接:https://www.haomeiwen.com/subject/qdwecctx.html