user4237435
user4237435

Reputation: 353

Inheritance in Swift is a bit confusing

How does inheritance work in Swift? From my understanding all parents should be replaceable by their children. For some reasons it is not working. Below is an example:

public class Car {

var model: String

func getModel()-> String?{
   return model
}
}


 public class CompactCar: Car {
  // some codes

 }

public class carRedo{
 var cartyp:Car!
init(carType: Car){
   self.cartyp = carType
}
}

when I pass the CompactCar to carRedo constructor I am getting a compiling error:

carRedo(CompactCar)// error

This the error:

Cannot convert value of type '(CompactCar).Type' (aka 'CompactCar.Type') to expected argument type 'Car'

Upvotes: 4

Views: 69

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

You cannot pass CompactCar (or any other class name, for that matter) to the constructor of carRedo. You need to pass an object of type CompactCar instead:

let mini = CompactCar()
let redo = carRedo(mini)

If you do not need to access the car that you pass to carRedo separately, you could "fold" the two calls above into one:

let redo = carRedo(CompactCar())
//                           ^^

Upvotes: 5

Related Questions