Swift

Structs

Making variables made of more variables

What are Structs?

Structs are also a way we can define data. They are complex data types, which means that they can hold multiple data types. Let’s make our first struct.

struct Book {
    var color: String
    var pages: Int
}

Inside of the Book struct, we said it contains two variables: A String named color, and an Integer named pages. Below is an example of us using this Struct. Here we initialize 2 seperate books using different values for color and pages. Then, we print a specific bit of info about each ‘Book’ that we’ve created from the Struct.

let diaryOfAWimpyKid = Book(color: "Red", pages: 221)
let captainUnderpants = Book(color: "Blue", pages: 125)
print(diaryOfAWimpyKid.color)
print(captainUnderptants.pages)

We can also copy this struct initialization into a separate variable and modify that variable, without changing the original. This will be useful for duplication and other concepts we’ll have to deal with during app development.

var bookCopy = diaryOfAWimpyKid
bookCopy.color = "Green"
    
print(diaryOfAWimpyKid)
print(bookCopy)

Functions in Structs

We can also put functions inside structs, which allow us to receive and manipulate data easier inside the struct. For example, we could have a description function.

struct Book {
    var color: String
    var pages: Int
        
    func description() {
        print("This book is \(color) and has \(pages) pages.")
    }
}

However, when a function is inside a struct, we call it a method.

We can run or ‘call’ this method by writing:

diaryOfAWimpyKid.description() 
// This is specific for the diaryOfAWimpyKid book. 
// Different books would be 'called' with their own 
// names before the period.

What's next?

Next, we will go over another complex data type called Classes. They have lots of different capabilities compared to structs, that allow you to do tons of different things.

chevron_up