• Swift中的类型相关内容


     

     Any、AnyObject

    1、Swift提供了2种特殊的类型:Any、AnyObject

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

            AnyObject可以代表任意类类型(在协议后面写上AnyObject,代表只有类能够遵守这个协

            议)

    1. class Person {
    2. }
    3. var stu: Any = 10
    4. stu = "Jack"
    5. stu = Person()

     is、as?、as!、as

    1、is用来判断是否为某种类型,as用来做强制类型转换

    1. class Person {
    2. func study() {
    3. }
    4. }
    5. var stu: Any = 10
    6. (stu as? Person)?.study()
    1. var data = Array<Any>()
    2. data.append(2 as Any)

    X.self、X.Type、AnyClass

    1、X.self是一个元类型(metadata)的指针,metadata存放着类型相关信息

    1. class Person {
    2. }
    3. Person.self

    2、X.self是属于X.Type类型

     

    Person.Type是堆空间对象的前八个字节,也就是元类型地址值。

    1. class Person {}
    2. class Student: Person {}
    3. var perType: Person.Type = Person.self
    4. var stuType: Student.Type = Student.self
    5. perType = Student.self
    1. class Person {}
    2. class Student: Person {}
    3. var anyType: AnyObject.Type = Person.self
    4. anyType = Student.self
    5. public typealias AnyClass = AnyObject.Type
    6. var anyType2: AnyClass = Person.self
    7. anyType2 = Student.self
    1. var per = Person()
    2. var perType = type(of: per)//非函数调用,直接取出per的前八个字节
    3. print(Person.self == perType) // true

    元类型的应用

    1、元类型类似于OC里面的class,可以用于动态初始化

    1. class Animal {
    2. required init() {}
    3. }
    4. class Cat: Animal {}
    5. class Dog: Animal {}
    6. class Pig: Animal {}
    7. func create(_ classes: [Animal.Type]) -> [Animal] {
    8. var arr = [Animal]()
    9. for cls in classes {
    10. arr.append(cls.init())
    11. }
    12. return arr
    13. }
    14. print(create([Cat.self, Dog.self, Pig.self]))

    2、可以通过元类型调用runtime的一些API。Swift有一个隐藏的基类,swift._swiftObject

    Self

    1、Self一般用作返回值类型,限定返回值跟方法调用者必须是同一类型(也可以作为参数类型)

    1. protocol Runnable {
    2. func test() -> Self
    3. }
    4. class Person: Runnable {
    5. required init() {}
    6. func test() -> Self {
    7. type(of: self).init()
    8. }
    9. }
    10. class Student: Person {}
    11. var stu = Student()
    12. stu.test() //Student

    2、如果Self用在类中,要求返回时调用的初始化器是required的

  • 相关阅读:
    PointNet++论文及代码详解
    数据库性能测试实践:慢查询统计分析
    Ubuntu: 系统使用, 系统源更新, Vi基本操作, 磁盘拓展
    学习笔记-sliver
    el-select 远程搜索下,添加下拉箭头
    网页头部的声明应该是用 lang="zh" 还是 lang="zh-CN"?
    Windows11 手把手教授开放端口
    MySQL派生表合并优化的原理和实现
    Vue前端框架快速入门学习笔记
    将IEEE制浮点数转换为十进制
  • 原文地址:https://blog.csdn.net/run_in_road/article/details/126020459