Luciano Falco
Luciano Falco

Reputation: 101

How to pass a superclass instance as an argument for a subclass instance declaration?

I want to pass a superclass instance as a parameter for a subclass declaration. For example:

class Dog {
      var bone: Int
      var collar: String

  init(bone: Int, collar: String){
  self.bone = bone
  self.collar = collar
}

class Doggy: Dog {
  var toy: Int

  init(bone: Int, collar: String, toy: Int){
  self.toy = toy
  super.init(bone: Int, collar: String)
  }
}

var Spike = Dog(bone:3, collar:"lol")
var Nik = Doggy(bone:3, collar: "lol", toy: 5)

Now, instead of the last line, I want something like

var Nik = Doggy(Spike, toy: 5)

Is there an easy way to achieve that? Thanks in advance

Upvotes: 0

Views: 35

Answers (2)

Quoc Nguyen
Quoc Nguyen

Reputation: 3007

Yes, add another init to your Doggy class

convenience init(_ dog: Dog, toy: Int) {
    self.init(bone: dog.bone, collar: dog.collar, toy: toy)
}

You can call

var Nik = Doggy(Spike, toy: 5)

Upvotes: 0

rrkjonnapalli
rrkjonnapalli

Reputation: 447

Method overloading will help you. You should handle the situations. See here for reference: https://www.geeksforgeeks.org/function-overloading-c/ i.e, there'll be different init methods.

Upvotes: 1

Related Questions