Swift override class func

14,914
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.

Share:
14,914
Nikita Arkhipov
Author by

Nikita Arkhipov

Check out my awesome ios animation framework Animatics that will save you tone of time!

Updated on June 18, 2022

Comments

  • Nikita Arkhipov
    Nikita Arkhipov almost 2 years

    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?

  • matt
    matt about 9 years
    And see the discussion in my Swift book on this topic: apeth.com/swiftBook/ch04.html#_type_reference
  • matt
    matt about 9 years
    Note that if getInnerValue were a class method, self would be the right target.
  • BallpointBen
    BallpointBen about 7 years
    In Swift 3, self.dynamicType has become type(of: self).