一步步学习Swift

Swift学习之Any、AnyObject、AnyClass

2020-09-24  本文已影响0人  冷武橘

一、Any和AnyObject

Any:可以代表任意类型(枚举、结构体、类,也包括函数类型)
AnyObject:可以代表任意类类型。

class Student {
    func test(){
    }
}

struct size {
    var width:Float
    var height:Float
}
var a:Any = 1.2
a = 10
a = "eeee"
a =  [10,20]
a = UIView()
a = Student()
a = Student().test()
var anyObject:AnyObject = Student()
anyObject = UIView()

二、AnyClass

元类型(metadata)就是类型的类型,一个元类型指针存放着类型相关的信息。X.self就可以获得一个元类型。

class Student {}
var vcType:UIViewController.Type  = UIViewController.self
var studentType:Student.Type  = Student.self
var viewType:UIView.Type = UIView.self
var  sObject: AnyObject = Student()
var  vObject:AnyObject = UIView()

var SType:AnyObject.Type =  Student.self
var VType:AnyObject.Type = UIView.self
import UIKit
class Student {}
var v:AnyObject = Student()
var Vtype:AnyObject.Type = Student.self
var Vcalss:AnyClass =  Student.self

总结:
Any代表任意类型;
AnyObject代表任意类类型;
X.self 获取一个元类型指针;
X.Type代表一个X元类型
AnyObject.Type 代表任意元类型;
AnyClass = AnyObject.Type

三、AnyClass初始化一个实例对象

AnyObject.Type 可以通过init()得到一个实例

class Student{
    required init(){}
}
let sType = Student.self
let student = sType.init()
print(student)

四、根据字符串初始化一个控制器

Vicent  15:31:52
   func getClassFromString(string:String) -> UIViewController? {
        let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"]as!String
        guard let anyObjectType: AnyClass = NSClassFromString(namespace + "." + "\(string)") else {
            return nil
        }
        let vcType = anyObjectType as! UIViewController.Type
        let vc:UIViewController = vcType.init()
        return vc
    }
上一篇 下一篇

猜你喜欢

热点阅读