self && Self
2023-08-28 本文已影响0人
tom__zhu
self 用在实例方法或是类方法中,返回的是当前实例或是当前类的类型。
Self 只能用作函数关键字,表示当前类型,且只能用在方法返回类型中。
self 举例
// 实例方法
class Dog {
func run() {
print("\(self) run")
}
}
// 输出
DEMO_.Dog run
// 类方法
class Dog {
static func spark() {
print("\(self) spark")
}
}
// 输出
Dog spark
Self 举例
class Dog: Myprotocol {
func getYourDog() -> Self { // Self表示方法返回类型
return self
}
func getYourDog_() -> Dog { // 返回值是Dog类型,和Self是等价的
return self
}
}
protocol Myprotocol {
func getYourDog() -> Self // 协议中,Self表示返回类型
}
Self 表示在方法返回值类型,上面Self和Dog作为方法返回值类型是相同的意思。