Swift5.1学习随笔之X.self、X.Type、AnyCl

2020-05-06  本文已影响0人  SAW_
class Person { }
var p = Person()

上面的例子🌰中:Person对象放在堆空间,指针变量p存储的是Person堆空间地址值。堆空间变量中的前8个字节存储的是元类型的地址值,存放着类型相关信息,存放在另外一块内存。

Person.self8个字节,放着元类型的地址,跟Person()对象前8个字节放的东西是一样的

var pType:Person.Type = Person.self
class Person { }
class Student: Person { }
var perType: Person.Type = Person.self
var stuType: Student.Type = Student.self
perType = Student.self
var anyType: AnyObject.Type = Person.self
anyType = Student.self
public typealias AnyClass = AnyObject.Type
var anyTYpe2: AnyClass = Person.self
anyTYpe2 = Student.self

元类型的应用
class Animal {
    required init() { }
}
class Cat: Animal { }
class Dog: Animal { }
class Pig: Animal { }

func creat(_ clses: [Animal.Type]) -> [Animal] {
    var arr = [Animal]()
    for cls in clses {
        arr.append(cls.init())
    }
    return arr
}

print(creat([Cat.self, Dog.self, Pig.self]))
上一篇下一篇

猜你喜欢

热点阅读