Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 931
Nikita Arkhipov Avatar asked Mar 26 '15 15:03

Nikita Arkhipov


1 Answers

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.

like image 125
matt Avatar answered Oct 28 '22 10:10

matt