- 大写的
Self代表当前类型
class Person {
var age = 1 // 实例属性(对象属性)
static var count = 2 // static、class修饰代表为类属性
func run() {
print(self.age)
print(Self.count) //Self代表的是Person类型,相当于Person.count
}
}
Self一般用作返回值类型,限定返回值跟方法调用者是同一类型(也可作参数类型)
protocol Runnable {
func test() -> Self
}
class Person: Runnable {
required init() {}
func test() -> Self {
type(of: self).init()
}
}
class Student: Person {init() {}}
使用
var p = Person()
print(p.test()) // Person
var s = Student()
print(s.test()) // Student