LateNate LateNate - 1 year ago 60
Swift Question

Default values within a class

Lets just say i have the following class:

class car {
var brand = ["BWM", "Ford", "Audi","Toyota"
var color = ["Red", "Blue", "White", "Black"
var speed = Double()
var weight = Double()

I have a UITableView that allows the user to add a row, and pick a new car based on the brand.

Now lets say all BMWs are red, so color is set to red.
I think I could achieve this by adding:

If brand == "BMW"{
color = "red"}

But I also want to set defaults for other brands, and this seems like a long way of doing things. Is there an easier way?

Answer Source

I think you should re-evaluate your class. A single car doesn't have multiple brands, so your brand property should be an enumeration, as should your colour.

Once you define a Car class, A BMW is then a subclass of a Car where you override the initialisation behaviour:

enum CarBrand {
    case BMW
    case Ford
    case Audi
    case Toyota

enum CarColor {
    case Red
    case Blue
    case White
    case Black

class Car {
    var brand: CarBrand
    var color: CarColor
    var weight: Double
    var maxSpeed: Double

    init(brand: CarBrand, color: CarColor, weight: Double, maxSpeed: Double) {
        self.brand = brand
        self.color = color
        self.weight = weight
        self.maxSpeed = maxSpeed

class BMWCar : Car {
    init(weight: Double, maxSpeed: Double) {
        super.init(brand: .BMW, color: .Red, weight: weight, maxSpeed: maxSpeed)

let aCar = Car(brand: .Audi, color: .Blue, weight: 1760, maxSpeed: 200)

let aBMWCar = BMWCar(weight: 1800, maxSpeed: 220)

Strictly speaking Car should be an abstract class, but this isn't supported directly in Swift.