## Checkpoint 6

I've seen a clearer solution to this checkpoint, but it was shifting gear by 1, and I created it so it can shift by any number unless it's higher/lower then the capabilities of that car. I think it's little bit more complicated but it works. Could someone tell me how can I write this code more efficiently and simpler ?

``````import UIKit

struct Car {

let model: String
let numberOfSeats: Int
var currentGear = 0 {
didSet {
switch currentGear {
case 1...10:
print("You are now in gear \(currentGear)")
case 0:
print("You are now in neutral")
default:
print("I don't know in which gear you are in")
}
}
}

mutating func gearUp(by gear: Int) {
switch currentGear + gear {
case 1...10:
self.currentGear += gear
default:
print("You cannot shift to this gear. This gear doesn't exist in your car")
}
}

mutating func gearDown(by gear: Int) {
switch currentGear {
case 1...10:
if currentGear >= gear {
self.currentGear -= gear
} else {
print("You cannot shift down by \(gear) gear(s). Current gear is \(currentGear)")
}
case 0:
print("You are already in neutral. Cannot shift down.")
default:
print("You cannot shift to this gear. This gear doesn't exist in your car")
}
}

}

var car = Car(model: "Porsche 911", numberOfSeats: 2, currentGear: 0)

car.gearUp(by: 10)

car.gearDown(by: 10)
``````

Could someone tell me how can I write this code more efficiently and simpler ?

Jumping ahead a little bit, take a look at how you can remove this awkward code using inflection.

``````..... } else {
//                                        👇🏼    Ugh!
print("You cannot shift down by \(gear) gear(s). Current gear is \(currentGear)")
}``````

#### Keep Coding

1

``````struct Car {
let model: String
let numberOfSeats: Int
private(set) var currentGear: Int

init(model: String, numberOfSeats: Int) {
self.model = model
self.numberOfSeats = numberOfSeats
self.currentGear = 0
}

mutating func gearUpDown(state: String) {
if state.lowercased() == "up" {
if currentGear < 5 {
currentGear += 1
}
} else {
if currentGear > 0 {
currentGear -= 1
}
}

}
}``````

1

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.