Search code examples
swiftinheritanceinitializationsubclassing

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()

Solution

  • 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()