Swift - Self

作者: aven_kang | 来源:发表于2022-04-11 00:45 被阅读0次
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方法的时候,基本上是谁调用返回谁

相关文章

网友评论

    本文标题:Swift - Self

    本文链接:https://www.haomeiwen.com/subject/ftzerrtx.html