Lukej2680 Tech Blog

Checkpoint 3

This post covers checkpoint 6 from 100 Days of Swift - Introduction to Swift module

Description
To check your knowledge, here’s a small task for you: create a struct to store information about a car, including its model, number of seats, and current gear, then add a method to change gears up or down. Have a think about variables and access control: what data should be a variable rather than a constant, and what data should be exposed publicly? Should the gear-changing method validate its input somehow?

Code

struct Car {
    private let model: String
    private let seats: Int
    private var gear = 1
    
    enum CarError: Error {
        case noGearError
    }
    
    init(model: String, seats: Int) {
        self.model = model
        self.seats = seats
    }
    
    mutating func gearShift(newGear: Int) throws -> Int {
        if newGear > 10 || newGear < 1 {
            throw CarError.noGearError
        } else {
            gear = newGear
            return 0
        }
    }
}

Explanation
Here I have created my first struct.

This project was taken from the HackingWithSwift website. However all code is original work by site owner.