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

Cycle created when a convenience initializer that overrides a designated initializer invokes an inherited convenience initializer

    XMLWordPrintable

    Details

      Description

      The following code compiles, but fails at runtime. I tried in an XCode playground and REPL.
      The Child class overrides all of the Parent class designated initializers, and therefore it automatically inherits all of the superclass convenience initializers. But the Parent convenience initializer reasonably delegates to it’s designated initializer, which has been overridden by the subclass. So it is not the Parent version of that 2-argument initializer that is invoked, but the overridden version. The overridden version takes advantage of the fact that the subclass has inherited Parent’s convenience initializer, and there it is - you have a cycle. I don’t know if this would be considered programmer-mistake or a compiler bug.

      I'm using Apple Swift version 2.1.1 (swiftlang-700.1.101.15 clang-700.1.81).

      class Parent {
        var parentProperty1:String
        var parentProperty2:String
        
        init(parentProperty1:String, parentProperty2:String) {
          self.parentProperty1 = parentProperty1
          self.parentProperty2 = parentProperty2
        }
        
        convenience init(parentProperty1:String) {
          print("in the Parent convenience initializer")
          self.init(parentProperty1:parentProperty1, parentProperty2:"nada")
        }
      }
      
      class Child : Parent {
        var childProperty:Double
        
        init(parentProperty1: String, parentProperty2:String, childProperty:Double) {
          self.childProperty = childProperty
          super.init(parentProperty1: parentProperty1, parentProperty2:parentProperty2)
        }
        
        // It seems that this trips up the compiler?
        convenience override init(parentProperty1:String, parentProperty2:String) {
          //this invokes the inherited convenience initializer, which invokes this overidden
          //version of the parent's designated initializer, which invokes the inherited convenience initializer,
          // cycle repeats until crash.
          print("in the subclass overridden convenience-version of the parent designated initializer")
          self.init(parentProperty1:parentProperty1)
        }
      }
      
      let child = Child(parentProperty1: "This is", parentProperty2: "the central scrutinizer")
      print("\(child.parentProperty1)...\(child.parentProperty2). childProperty: \(child.childProperty)")
      

        Attachments

          Activity

            People

            Assignee:
            Unassigned
            Reporter:
            sflahave Shawn Flahave
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Dates

              Created:
              Updated: