当前位置:网站首页>Swift中的类型相关内容
Swift中的类型相关内容
2022-08-02 22:30:00 【扑腾的蛾子】
Any、AnyObject
1、Swift提供了2种特殊的类型:Any、AnyObject
Any可以代表任意类型(枚举、结构体、类,也包括函数类型)
AnyObject可以代表任意类类型(在协议后面写上AnyObject,代表只有类能够遵守这个协
议)

class Person {
}
var stu: Any = 10
stu = "Jack"
stu = Person()is、as?、as!、as
1、is用来判断是否为某种类型,as用来做强制类型转换
class Person {
func study() {
}
}
var stu: Any = 10
(stu as? Person)?.study()var data = Array<Any>()
data.append(2 as Any)X.self、X.Type、AnyClass
1、X.self是一个元类型(metadata)的指针,metadata存放着类型相关信息
class Person {
}
Person.self2、X.self是属于X.Type类型

Person.Type是堆空间对象的前八个字节,也就是元类型地址值。
class Person {}
class Student: Person {}
var perType: Person.Type = Person.self
var stuType: Student.Type = Student.self
perType = Student.selfclass Person {}
class Student: Person {}
var anyType: AnyObject.Type = Person.self
anyType = Student.self
public typealias AnyClass = AnyObject.Type
var anyType2: AnyClass = Person.self
anyType2 = Student.selfvar per = Person()
var perType = type(of: per)//非函数调用,直接取出per的前八个字节
print(Person.self == perType) // true元类型的应用
1、元类型类似于OC里面的class,可以用于动态初始化
class Animal {
required init() {}
}
class Cat: Animal {}
class Dog: Animal {}
class Pig: Animal {}
func create(_ classes: [Animal.Type]) -> [Animal] {
var arr = [Animal]()
for cls in classes {
arr.append(cls.init())
}
return arr
}
print(create([Cat.self, Dog.self, Pig.self]))2、可以通过元类型调用runtime的一些API。Swift有一个隐藏的基类,swift._swiftObject
Self
1、Self一般用作返回值类型,限定返回值跟方法调用者必须是同一类型(也可以作为参数类型)
protocol Runnable {
func test() -> Self
}
class Person: Runnable {
required init() {}
func test() -> Self {
type(of: self).init()
}
}
class Student: Person {}
var stu = Student()
stu.test() //Student2、如果Self用在类中,要求返回时调用的初始化器是required的
边栏推荐
猜你喜欢

目前为止 DAO靠什么盈利?

Learn more TypeScript 】 【 TypeScript modular
![[TypeScript] Deep Learning of TypeScript Classes (Part 1)](/img/47/34954f1e01b844816d74f3ac556f9b.png)
[TypeScript] Deep Learning of TypeScript Classes (Part 1)

最新真实软件测试面试题分享,收藏了还怕进入不了大厂?

测试人生 | 阿里实习 90 天:从实习生的视角谈谈个人成长

The CTF command execution subject their thinking

Jmeter二次开发实现rsa加密

你离「TDengine 开发者大会」只差一条 SQL 语句!

AcWing 2983. 玩具

JS 包装类 Math对象 round max() min() random
随机推荐
AcWing 2983. 玩具
IDO代币预售合约系统开发技术详细
2022杭电多校第一场(K/L/B/C)
MySql查询某个时间段内的数据(前一周、前三个月、前一年等)
记一次mysql查询慢的优化历程
基于STM32的FLASH读写实验含代码(HAL库)
如何通过 IDEA 数据库管理工具连接 TDengine?
kubernetes pod podsecurityPolicies(PSP)
2022暑假牛客多校1 (A/G/D/I)
Based on two levels of decomposition and the length of the memory network multi-step combined forecasting model of short-term wind speed
go 序列化与反序列化
The CTF command execution subject their thinking
搭建直播平台,使用node生成验证码图片,并进行验证
谷粒商城-day14-商城业务与压力测试
刚安装完win10专业工作站版,系统变量中Path默认值有哪些?重新建一个“PATH”变量名,会覆盖掉原先的“Path”。
Mysql查看慢查询日志
openssl源码下载
最新真实软件测试面试题分享,收藏了还怕进入不了大厂?
Word operation: adjust the English font individually
Tanabata is here - the romance of programmers