UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Checkpoint 6 help

Forums > 100 Days of SwiftUI

Hi, Im stuck on changing gear method. Console give me gear: 0 - no mather what input i give.

The whole struct look like this:

struct Car {
    let model: String
    let seats: Int
    private(set) var gear = 1

    mutating func gearChange (currentgear: Int) {
        if currentgear <= 10 {
            gear -= 1
        } else if currentgear > 1 {
            gear += 1
        }
    }
}

var myCar = Car(model: "Saab 9-3", seats: 4)
myCar.gearChange(currentgear: 9)

print(myCar)

2      

Well, you are setting gear to 1 initially

private(set) var gear = 1

And your function looks like this

mutating func gearChange (currentgear: Int) {
        if currentgear <= 10 {
            gear -= 1
        } else if currentgear > 1 {
            gear += 1
        }
}

So, anytime you call the function with a currentGear of 10 or less, it is going to subtract 1 from gear. So gear will be equal to 0 at that point.

So when you call the function with a currentGear of 9

myCar.gearChange(currentgear: 9)

it enters your if closure because 9 is less than or equal to 10. So it subtracts 1 from gear which makes gear equal to 0.

If you call the function with a currentGear value greater than 10, it will skip your if closure, and enter your else if closure. So it will add 1 to gear each time. So you will end up with gear being equal to 2.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.