Uploaded image for project: 'Swift'
  1. Swift
  2. SR-1736

Super class method returning Self returns superclass type instead of Self

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Closed
    • Priority: Medium
    • Resolution: Done
    • Component/s: Compiler
    • Labels:
      None
    • Environment:

      Xcode Version 9.1 (9B55)
      Swift 4.0

      Description

      Calling parent class's method with return type Self is expected to return type Self. However, calling the method using 'super.methodName' returns the parent class's type instead of Self.

      class ParentWallet {
          var money: Int
          
          required init(money: Int) {
              self.money = money
          }
          
          func newWalletWithMoreMoney(_ moreMoney: Int) -> Self {
              let moneyForNewWallet = money + moreMoney
              return type(of:self).init(money: moneyForNewWallet )
          }
      }
      
      class ChildWallet: ParentWallet {
          required init(money: Int) {
              super.init(money: money)
          }
          
          override func newWalletWithMoreMoney(_ moreMoney: Int) -> Self {
              let newWallet = super.newWalletWithMoreMoney(moreMoney)    // newWallet has type ParentWallet instead of Self
              return newWallet    // Error: Cannot convert return expression of type 'ParentWallet' to return type 'Self'
          }
      }
      

      Without the override function in ChildWallet class, these are sample behaviors:

      // wallet1 has type ParentWallet
      let wallet1 = ParentWallet(money: 10).newWalletWithMoreMoney(5)
      // wallet2 has type ChildWallet
      let wallet2 = ChildWallet(money: 10).newWalletWithMoreMoney(5)
      

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            hanjustin Justin Hanki Lee
            Votes:
            1 Vote for this issue
            Watchers:
            6 Start watching this issue

              Dates

              Created:
              Updated:
              Resolved: