swift5.1学习-小知识

1.Any、AnyObject

Swift提供了2种特殊的类型:Any、AnyObject
Any:可以代表任意类型(枚举、结构体、类,也包括函数类型)
AnyObject:可以代表任意类类型(在协议后面写上: AnyObject代表只有类才能遵守这个协议)
在协议后面写上: class也代表只有类才能遵守这个协议

2.is、as?、as!、as

is用来判断是否为某种类型
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]() data.append(Int("123") as Any)
 var d = 10 as Double
print(d) // 10.0

3.X.self、X.Type、AnyClass

X是类名

X.self是一个元类型(metadata)的指针(8个字节,本质上是OC的isa指针),metadata存放着类型相关信息 ,相当于OC的X.class
X.self属于X.Type类型

 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
ar per = Person()
var perType = type(of: per) // Person.self 
print(Person.self == type(of: per)) // true

4.Self与self

self代表当前实例,Self代表当前类型
Self一般用作返回值类型,限定返回值跟方法调用者必须是同一类型(也可以作为参数类型)

 class Person {
    var age = 1
    static var count = 2
    func run() {
        print(self.age) // 1
        print(Self.count) // 2
    }
}
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())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力修福报

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值