100 Days of SwiftUI Day 10

100 Days of SwiftUI – Day 10 – Structs

After recovering from a difficult 9th day where we tackled closures, today, I went back refreshed to learn about structs in SwiftUI. Let’s dive in!

How to create a struct in SwiftUI

Swift lets us create our own custom, complex data types. These types can be kitted out with variables and functions. Here’s an example:

struct Formula1Driver {
    let name: String
    let team: String
    let carNumber: Int
}

let maxVerstappen = Formula1Driver(name: "Max Verstappen", team: "Red Bull Racing", carNumber: 1)

struct DartsPlayer {
    let name: String
    let mainSponsor: String
    let nickname: String
    let worldRanking: Int
}

let mvg = DartsPlayer(name: "Michael van Gerwen", mainSponsor: "Winmau", nickname: "Mighty Mike", worldRanking: 3)

Computing property values dynamically

A struct can have two types of properties: a stored property and a computed property. A stored property is a variable or a constant that holds fixed data, while a computed property get’s calculated dynamically whenever it’s accessed. We use getters and setters to make this easy.

struct Employee2 {
    let name: String
    var vacationAllocated = 14
    var vacationTaken = 0
    
    var vacationRemaining: Int {
        get {
            vacationAllocated - vacationTaken
        }
        set {
            vacationAllocated = vacationTaken + newValue
        }
    }
}

var maverick = Employee2(name: "Maverick", vacationAllocated: 14)

maverick.vacationTaken += 5
maverick.vacationRemaining = 10
print(maverick.vacationAllocated)

Using property observers

Swift features property observers, which is a bit of code that runs when a property changes. For example, in the example above, you may want to print something whenever a vacation is taken. You accomplish this by using a didSet and willSet observer. The first will run after a property has been changed, the latter before it will be changed. If you’re interested in knowing when you should use a property observer, Paul has got you covered.

struct FootballGame {
    let playerName: String
    var score = 0 {
        didSet {
            print("The new score is: \(score)!")
        }
        willSet {
            print("A new score is about to be entered! The current score is \(score),")
        }
    }
}

var fifa22 = FootballGame(playerName: "Maverick")
fifa22.score += 5

// prints:
// A new score is about to be entered! The current score is 0
// The new score is: 5.

Custom initializers

Initializers are methods that override the default way an instance of a struct is created. There is one important rule when creating custom initializers: whenever any initializer is called, all properties must have a value before the initializer ends.

struct CustomInitializer {
    var name:  String
    var number: Int
    
    // Custom init here
    init(name: String) {
        self.name = name
        number = Int.random(in: 1...99)
    }
    
    init(name: String, number: Int) {
        self.name = name
        self.number = number
    }
}

let mavvy = CustomInitializer(name: "Darryl", number: 5)
let savvy = CustomInitializer(name: "Savvy")
print(savvy.number)
print(mavvy.number)

And that was it for day 10! Tomorrow, we’ll be expanding on structs with access control, static properties and methods. Checkpoint 6 is also waiting for us. As always, we march on!

Darryl

Hi! My name is Darryl and this is my personal blog where I write about my journey as I learn programming! You'll also find articles about other things that interest me including games, tech and anime.

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

100 Days of SwiftUI – Day 53

100 Days of SwiftUI – Day 20 – Guess the Flag

100 Days of SwiftUI – Day 35

100 Days of SwiftUI – Day 17 – WeSplit