0

Im trying to connect two classes. I have a class of CarType and another one of Cars.

When I register a car in Cars then I want that car to be connected to a car type from the CarType class.

These are my classes

class CarType {
    var brand: String?
    var speed: Int?
    var fuel: Int?
    var serviceProvider: String?
    init(brand: String, speed: Int, fuel: Int, serviceProvider: String) {
        self.brand = brand
        self.speed = speed
        self.fuel = fuel
        self.serviceProvider = serviceProvider
    }
}

class Cars {
    var regNum: String?
    var nextMaint: String?
    var operatedBy: String?
    init(regNum: String, nextMaint: String, operatedBy: String) {
        self.regNum = regNum
        self.nextMaint = nextMaint
        self.operatedBy = operatedBy
    }
}

I tried to inherit CarType in Cars but that just confused me...

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 3
    Not related but why are you declaring all properties as optional but initialize them with non-optional values? **Don't do that. Never do that**. Remove all question marks. Never fear. You won't get any compiler error. – vadian Dec 01 '17 at 12:09
  • Thanks, will do that – Jónas Rafnsson Dec 01 '17 at 12:13
  • Also, `CarType` should probably be a struct rather than a class and the properties should be declared as `let` not `var` as they are immutable. Your `fuel` property should be an `enum` rather than an `int` – Paulw11 Dec 01 '17 at 12:43
  • 1
    Just a note, I would rename `Cars` to `Car` because it appears to be a single car. `Cars` sounds like a collection class of some sort. I think @Paulw11 has a good point about the fuel and it might need more clarity. Is it a quantity of fuel or a fuel type? You would want an enum for a fuel type and you might want a double if it's quantity. – Jeff LaFay Dec 01 '17 at 14:29

1 Answers1

3

Your Cars class should have a property named for example: carType and this property is of type CarType, like this:

var carType: CarType?

Each Cars instance initializes this property in the suitable way through the the initializer or by setting it later.

This is an example of an OOP concept called Composition, you can read more about it here and here.

By the way, it's better to change Cars class name to Car, because it models a single car.

Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36