Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Object-Oriented Swift Value vs Reference Types Final Challenge

Object-Oriented Swift Code Challenge: Final Challenge

I think I'm OK with the first class, but I'm stumped at initializing the Car class.

Vehicle.swift
class Vehicle {
    let wheels: Int
    let doors: Int

    // Designated initializer
    init(wheels:Int, doors:Int){
        self.wheels = wheels
        self.doors = doors
    }
}

class Car: Vehicle {
    // A car must default to 4 wheels and 4 doors
    init(wheels: Int, doors: Int){
      //call super.init

    }
}

3 Answers

most welcome! No it is not used to override a function. To override a function, we just use the override keyword before the function we want to override:

override func()

"_" is used because we want to give initial values to the parameters (wheels & doors) in the init declaration :

init( _ wheels: Int = 4, _ doors: Int = 4)

More Extra & helpful explanation in detail: If we are giving initial values to the parameters in the block of init(), there is no need to add "_" before parameter names :

init(wheels: Int, _doors: Int) {
wheels = 4
doors = 4
super.init(wheels: wheels, doors: doors)
}

But if we do like this, then we have initialised wheels and doors inside the init() code block, but in our program, wheels and doors are defined as constants

let wheels: Int
let doors: Int

But adding the "_" before the parameter name is the best practice, so we should follow it.

I would recommend you to watch the videos in that stage again, it will help you in better understanding.

I hope this would help :) Thanks

Here is the answer

class Vehicle {
    let wheels: Int
    let doors: Int

    // Designated initializer
    init(wheels:Int, doors:Int){
        self.wheels = wheels
        self.doors = doors
    }
}

class Car: Vehicle {
    // A car must default to 4 wheels and 4 doors
    init(_ wheels: Int = 4,_ doors: Int = 4){
      // call super.init
      super.init(wheels: wheels, doors: doors)
    }
}

Thanks!

Why the " _ " ? The only other time I saw this was to override a function.

Forgive any ignorance on my part, I looked at a line of code for the first time six months ago so this is all very new to me.

Thanks again.