Bronze Challenge No. 1:
This was probably the easiest challenge so far: just extend Int
to include a property on an int
that multiplies itself times 5.
extension Int {
var timesFive: Int { return self * 5 }
}
5.timesFive // returns 25
Bronze Challenge No. 2:
Pretty straightforward to make this refactor. Add a constant to the Car
struct, and then fix the errors that the compiler throws (you’ll have to remove the duplicate value in the extension, fix the init()
method, and also fix the instance that is created, since you’ll now be specifying the number of doors upon instantiation). I also added a precondition()
in the init()
method, just to make sure that you can only choose form 2 or 4 doors for now.
struct Car {
...
let nickname: String
let numberOfDoors: Int
...
}
extension Car: Vehicle {
var topSpeed: Velocity { return 180 }
var hasFlatbed: Bool { return false }
}
extension Car {
init(make: String, model: String, year: Int, numberOfDoors: Int) {
precondition(numberOfDoors == 4 || numberOfDoors == 2,
"You can only have a car with 2 or 4 doors in this example")
self.init(make: make,
model: model,
year: year,
color: "Black",
nickname: "N/A",
numberOfDoors: numberOfDoors,
gasLevel: 1.0)
}
}
var c = Car(make: "Ford", model: "Fusion", year: 2013, numberOfDoors: 2) // car is now a coupe
Silver Challenge
To fix this, I just went ahead with implementing a precondition()
in the emptyGas(by:)
function to stop execution of the program until you put a value less than the current gasLevel
.
extension Car {
mutating func emptyGas(by amount: Double) {
precondition(amount <= 1 && amount > 0,
"Amount to remove must be between 0 and 1.")
precondition(amount < gasLevel,
"Amount to remove is larger than the amount of gas left")
gasLevel -= amount
}
...
}
That rounds this chapter out.