简体   繁体   中英

Swift override class func

It is easy to override a method in Swift:

class A {
   func innerValue() -> Int { return 5 }
   func getInnerValue() -> Int { return innerValue() }
}

class B: A {
   override func innerValue() -> Int { return 8 }
}

B().getInnerValue() //returns 8

However I don't know how to do the same when I declare innerValue() as static (using the class keyword):

class A {
   class func innerValue() -> Int { return 5 }
   func getInnerValue() -> Int {
      return A.innerValue() //ok for compiler but returns 5 instead of 8
      return self.innerValue() //error: 'A' doesn't have a member named 'innerValue'
      return innerValue() //error: Use of unresolved identifier 'innerValue'
   }
}

class B: A {
   override class func innerValue() -> Int { return 8 }
}

B().getInnerValue()

So is it possible in Swift?

return A.innerValue() //ok for compiler but returns 5 instead of 8

From your comment, it sounds like what you want to do is refer the current instance's class polymorphically. If that's what you want, then don't send the innerValue() message to A ; that means A only. And don't send it to self , because the way you've written this, getInnerValue is an instance method, while what you want to call is a class method. Send it to self.dynamicType , the class of the current instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM