red ferrari 458 italia parked near gray building

100 Days of SwiftUI – Day 10 & Day 11

We’re moving into much more interesting territory now as we begin to look at how to create and use custom data types.

I’m still recovering from the trauma of closures but fortunately Day 10 introduces the slightly simpler idea of a struct, a custom data type. We then move into some more advanced areas of this topic such as computed properties, get, set, didSet and willSet before covering custom initialisers. Quite a lot of this is new to me but it’s fairly intuitive thankfully.

Day 11 talks about how to control access to the properties and methods of a struct using the private keyword (and some variations) which prevents external functions from making changes they shouldn’t be able to. We also look at making properties and methods static. I struggle a little with this concept in the beginning but after watching the video a couple of times I think I understand the purpose and why you’d want to use such a thing.

Checkpoint 6

Our checkpoint today is an interesting one. We need to create a struct representing a car including its model, number of seats and current gear. We’ve also to include a method for changing gear and we have to decide whether to make anything in the struct private.

There’s clearly a lot of ways to go about this challenge. I decide to make my currentGear property private(set) which means it can be read externally but not modified. This has the benefit of meaning I don’t need to define a custom init method. I also choose to represent my gear changes as an enum with two cases and then build a switch statement to handle the different cases.

I could’ve gone further here, perhaps incorporating proper error handling, but I chose not to as it seemed a bit overkill.

struct Car {
    let model: String
    let seats: Int
    private(set) var currentGear = 0
    
    enum Direction {
        case up, down
    }
    
    mutating func changeGear(direction: Direction) {
        switch direction {
        case .up:
            if currentGear >= 10 {
                print("You're in top gear already!")
            } else {
                currentGear += 1
            }
        case .down:
            if currentGear <= 0 {
                print("You're in neutral and we don't have a reverse gear!")
            } else {
                currentGear -= 1
            }
        }
        print("Now in gear \(currentGear)")
    }
}