James C
James C

Reputation: 17

Can you pick and choose what gets inherited in a sub-class in Swift?

I have a base class (Spaceship) that has some variables and an initializer. I also have a subclass (UFO) that only needs one of the variables of the superclass. When I try and create a basic UFO object, I get: "missing argument for parameter 'weapon' in call var c = UFO()" I realize that error message is asking for a weapon parameter, but how do I (and is it even possible?) to create a basic UFO object that doesn't need a weapon parameter?

Have spent hours tinkering with "override", "init" and "super" commands. I've read a lot of the articles here on SO and other sites, but have not seen any examples similar to my situation. Again, I'm assuming that what I want to do is possible to begin with.

class Spaceship {

    var isUFO = false  
    var weapon:String 

     init(weapon:String) {      
         self.weapon = weapon
     }

    func printSomething() {
     print("Test")
    }
}

class UFO: Spaceship {
}


var a = Spaceship(weapon:"Laser")
a.printSomething() //OUTPUT: Test

var b = UFO(weapon:"")  
          //This runs, but I don't want to have to fill in parameters
b.printSomething()    //OUTPUT: Test

var c = UFO()       //Ultimately this is what I want to do
c.printSomething()  
       //OUTPUT: missing argument for parameter 'weapon' in call var c =    UFO()

Upvotes: 1

Views: 62

Answers (2)

Andreas Oetjen
Andreas Oetjen

Reputation: 10209

First, when using inheritence, you'll have to think about an "is a" relationship: An UFO is a spaceship. So when each spaceship has a weapon, and an UFO is a spaceship, then every UFO also has to have a weapon.

What you could do is make your weapon an optional, but I think this is somehow a mis-usage. Also, re-think your isUFO property:

  • A spaceship should not make assumptions about special subclasses
  • You could use the is operator to check the dynamic type of a Spacehip

If you don't want this inheritence behaviour, you might better think about something else, like protocols, where you only specify certain behaviour but no memory layout.

Upvotes: 1

PGDev
PGDev

Reputation: 24341

What you can do is mark weapon as optional String. Also, in init(weapon:) use default value of weapon as nil, i.e

class Spaceship {
    var isUFO = false
    var weapon: String? //here...

    init(weapon: String? = nil) { //here...
        self.weapon = weapon
    }

    func printSomething() {
        print("Test")
    }
}

Now, you can simply create the object of class UFO both with and without weapon, i.e.

var a = Spaceship(weapon:"Laser")
var b = UFO(weapon:"Another Weapon")
var c = UFO()  

Upvotes: 1

Related Questions