一、is、as?、as!、as
protocol Runnable {
func run()
}
class Person {}
class Student : Person, Runnable {
func run() {
print("Student run")
}
func study() {
print("Student study")
}
}
var stu: Any = 10
print(stu is Int) // true
stu = "Kac"
print(stu is String) // true
stu = Student()
print(stu is Person) // true
print(stu is Student) // true
print(stu is Runnable) // true
var stu: Any = 10
(stu as? Student)?.study() // 没有调用study
stu = Student()
(stu as? Student)?.study() // Student study
(stu as! Student).study() // Student study
(stu as? Runnable)?.run() // Student run
二、X.self、X.Type、AnyClass
- X.self 是一个元类型(metadata)指针,metadata存放着类型相关信息
- X.self 属于X.Type
- public typealias AnyClass = AnyObject.Type
- AnyClass 即任意类类型
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
var anyType2: AnyClass = Person.self
anyType2 = Student.self
- 可以利用type(of: obj) 查一个对象的类型
var per = Person()
var perType = type(of: per) // Person.self
print(Person.self == type(of: per)) // true
三、元类型的应用
class Animal {
required init() {}
}
class Cat: Animal {}
class Dog: Animal {}
class Pig: Animal {}
func create(_ clses: [Animal.Type]) -> [Animal] {
var arr = [Animal]()
for cls in clses {
arr.append(cls.init())
}
return arr
}
print(create([Cat.self, Dog.self, Pig.self]))
print(class_getSuperclass(Animal.self)!) // Swift._SwiftObject
四、Self
class Animal {
var age = 1
static var count = 2
required init() {}
func run() {
print(self.age) // 1
print(Self.count) // 2
}
}
- Self 一般用作返回值类型,限定返回值跟方法调用者必须是同一个类型(也可以作为参数类型)
protocol Runnable {
func run() -> Self
}
class Animal : Runnable {
required init() {}
func run() -> Self {
type(of: self).init()
}
}
class Cat: Animal {}
class Dog: Animal {}
var a = Animal()
// a type is Animal
print("a type is ", a.run())
var d = Dog()
// d type is Dog
print("d type is ", d.run())
网友评论