Swift笔记 - 09.Any、AnyObject、is、as?、as!、as、X.self、X.

Swift笔记 - 09.Any、AnyObject、is、as?、as!、as、X.self、X.Type、AnyClass、元类型、Self

Any、AnyObject

var stu: Any = 10
stu = "Jack"
stu = Student()

/创建1个能存放任煮类型的数组
// var data = Array<Any>()
var data = [Any](https://luowei.github.io/list/)
data.append(1)
data.append(3.14)
data.append(Student())
data.append("Jack")
data.append({ 10 })

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 = "Jack"
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

var data = [Any](https://luowei.github.io/list/)
data.append(Int("123") as Any)

var d = 10 as Double
print(d) // 10.0

X.self、X.Type、AnyClass

class Person { }
class Student: Person { }
var perType: Person.Type = Person. self
var stuType: Student.Type = Student.self
perType = Student.self

var anyType: Any0bject.Type = Person.self
anyType = Student.self
public typealias AnyClass = AnyObject.Type
var anyType2: AnyClass = Person.self
anyType2 = Student.self

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](https://luowei.github.io/list/)
    for cls in clses {
        arr.append(cls.init())
    }
    return arr
}
print(create([Cat.self, Dog.self, Pig.self]))

import Foundation
class Person {
    var age: Int = 0
}
class Student : Person {
    var no: Int = 0
}
print(class_getInstanceSize(Student.self)) // 32
print(class_getSuperclass(Student.self)!) // Person
print(class_getSuperclass(Person.self)!) // Swift._Swiftobject
class Person {
    static var age = 10
    static func run() {}
}
Person.age = 0
Person.run()

Person.self.age = 10
Person.self.run()
var p0 = Person() // init()
var p1 = Person.self() // init()
var p2 = Person.init() // init()
var p3 = Person.self.init() // init()
// var pType0 = Person
var pType1 = Person.self
func test(_ cls: AnyClass) {
}
test(Person.self)

Self关键字

protocol Runnable {
    func test() -> Self
}
class Person: Runnable {
    required init() { }
    func test() -> Self { type(of: self).init() }
}
class Student : Person { }

var p = Person()
// Person
print(p.test())
var stu = Student ()
// Student
print(stu.test())

版权所有,转载请注明出处 luowei.github.io.