Self 代表当前类型
Self一般用作返回值类型,限定返回值跟方法调用者必须是同一类型(也可以作为参考类型)
protocol Runnable {
func test() -> Self
}
class Person : Runnable {
var age:Int = 10
var name:String = ""
static var count = 2
func run() {
print(self.age)
print(Self.count)
}
required init() {}
init(age:Int,name:String) {
self.age = age
self.name = name
}
func test() -> Self {
type(of: self).init()
}
}
class Student : Person {}
var p = Person()
print(p.test()) // Person
var stu = Student()
print(stu.test()) // Student
不同的类,在调用test方法的时候,基本上是谁调用返回谁
网友评论