Programming & Tech Tips for Everyone

Structs

In the previous chapters, you have worked with data types like Int, String, Double.

But did you know you can also implement your own custom data type?

In Swift, one way to do this is by using a struct.

For example:

struct Person {
    var name: String
    var age: Int
}

// Create a Person object
let person1: Person = Person(name: "Alice", age: 32)

// Show info about the Person object
print(person1.name, person1.age)

Output:

Alice 32

In this chapter, you are going to learn how to create your own custom data type using a struct. These custom data types help you organize code and information. More importantly, it introduces you to object-oriented programming.

This chapter is part of a completely free Swift for Beginners guide. Make sure you have completed all the chapters from the start before reading this one.

Disclaimer: To learn Swift, you have to repeat everything you see in this guide and in the following guides. If you only read the guides, you are not going to learn anything!

Structs in Swift

In Swift, a struct allows you to create a custom data type.

Then you can use the custom type to create objects in your code.

With a struct, you can bundle related information together. You can store variables, constants, and functions into structs.

For instance, if you want to create users in your app, you can implement a struct to represent them.

The best way to understand structs is by solving a problem with them.

Consider this piece of code:

var name = "Alice"
var age = 32
var hobby = "Golf"

As you can see, these variables seem to describe a person called Alice who is 32 years old and plays golf.

But nowhere in the code does it say these variables belong to some person. This is just something we made up.

If you want these variables to represent a person, you need to specify a custom data type

This custom data type bundles these variables together.

To specify a custom data type, you can implement a struct.

Before writing our first struct, let’s see the syntax of creating one.

Syntax

The syntax for creating a struct in Swift is:

struct name {
   // properties
}

Where:

  1. struct keyword tells Swift there is going to be a new data type.
  2. name is the name of the data type. This should be a descriptive name to represent the data.
  3. Inside the curly brackets, you specify the variables, constants, and functions that belong to the struct. These are called properties.

Example 1.

With the basic theory out of the way, let’s create your first struct.

This struct is going to represent a person called Alice who is 32 years old and plays golf:

struct Person {
    var name = "Alice"
    var age = 32
    var hobby = "Golf"
}

Now you can create an object that represents this person and store it in a variable:

var person = Person()

As you can see, creating a struct object reminds calling a function as you need to use the name of the struct followed by a set of parenthesis.

Now, you can read the properties of this object by using the dot notation followed by the property name.

For example, let’s access the name, age, and hobby of the person:

print(person.name)
print(person.age)
print(person.hobby)

Output:

Alice
32
Golf

Because the person is a variable, you can also change its properties.

For example:

person.name = "Bob"
person.age = 28
person.hobby = "Jogging"

print(person.name)
print(person.age)
print(person.hobby)

Output:

Bob
28
Jogging

This demonstrates well how you can work with structs and objects in Swift.

Now you could create more Person objects like this:

var person1 = Person()
var person2 = Person()
var person3 = Person()

However, now they all are Alice, 32, playing golf.

But what if you want to create a completely new Person object without it being Alice at first.

In this case, you need to allow what is called initialization.

In the next section, you are going to learn how to do this with structs using a memberwise initializer.

Memberwise Initializer

To initialize new objects from a struct, you need to utilize the memberwise initialization process.

Let’s continue with the person struct from the previous section.

To use the memberwise initialization, implement the Person struct such that it only specifies the property names and their data types. But do not give them initial values!

This is best demonstrated with an example.

Example

Let’s create a Person struct that represents a Person with a name, age, and hobby.

However, this time we do not know these properties in advance.

Here is the Person struct:

struct Person {
    var name: String
    var age: Int
    var hobby: String
}

As you can see, now name, age, and hobby are unspecified. The only thing we know is the data type of these properties.

To create a Person object, pass the properties as parameters to it.

For example, let’s create a bunch of persons:

var person1 = Person(name: "Alice", age: 32, hobby: "Golf")
var person2 = Person(name: "Bob", age: 39, hobby: "Jogging")
var person3 = Person(name: "Charlie", age: 25, hobby: "Gym")

This initializes three new Person objects in your program.

Behind the scenes, Swift assigns each argument to the property specified in the structure.

This is what the memberwise initialization looks like.

Now you understand how to create a custom type in your code. You also know how to initialize these custom objects with the memberwise initialization process.

Next, let’s add some action to the struct by implementing a function in it.

Methods: Functions in Structs

In Swift, you can implement a function into a struct.

If did not read the chapter about functions yet, you can find it here.

When a function is created inside a struct, it is called a method.

When you create an object of the struct, you can use the dot notation to call the method on the object.

This is best demonstrated with an example.

Let’s continue with the Person struct.

At this point, the struct stores variables name, age, and hobby.

Now, let’s add a method that introduces a Person object.

In other words, you need a function that prints some information about the Person object into the console.

Here is how it looks in code:

struct Person {
    var name: String
    var age: Int
    var hobby: String

    func introduce() {
        print("Hi, I am", name, "and I love", hobby)
    }
}

The introduce() method has an access to the name, age, and the hobby of itself.

Now you can create a Person object and introduce it by calling the introduce() method:

var person1 = Person(name: "Alice", age: 32, hobby: "Golf")
person1.introduce()

Output:

Hi, I am Alice and I love Golf

As you probably guessed, you can call this introduce() method on any Person object you ever create.

At this point, you have created a struct that represents a person. It stores the name, age, and hobby of a person. In addition, the person knows how to introduce itself.

Implementing structs like this is super important. It allows you to write modular code that is logically grouped and easy to maintain.

Sneak Peek: Structs in Action

Did you know you have been using structs since the very first chapter in this entire series?

This is because data types like Int, String, or Double are all structs behind the scenes.

For example, to know how many characters there are in a String object, read its count property.

let name: String = "Alice"
print(name.count)

Output:

5

This means somewhere in the root files of Swift, there is a piece of code that looks something like this:

struct String {
    var count: Int
}

To keep it in scope, we are not going to dig deeper into the implementation details of Swift.

To take home, almost every data type you use is implemented as structs in Swift. Furthermore, in larger projects, you have to write custom data types with structs.

At this point, you have learned how to create a custom type in your Swift project using a struct. Most of the time, this is what you should use. However, in some particular situations, a struct is not enough. In this case, you need to use a class.

In the next chapter, you are going to learn how to create a custom data type using a class instead of a struct.

Next chapter: Classes in Swift

Conclusion

In this chapter, you learned how to use structs in Swift.

To recap, a struct makes it possible to create a custom data type in your code.

This is useful as you can group related values together.

struct Person {
    var name: String
    var age: Int
}

The way you represent these structs in Swift is by creating objects and assigning them to variables.

let person1: Person = Person(name: "Alice", age: 32)

You can then access the properties of these objects in your code.

print(person.name, person.age)

More importantly, you can also modify the properties (assuming they are variables, not constants).

person.name = "Bob"
person.age = 45

A key feature of structs is you can add functions, or methods, to them.

struct Person {
    var name: String
    var age: Int

    func info() {
        print("My name is", name, "and I am", age, "years old.")
    }
}

You can call these methods on the objects.

let person = Person(name: "Alice", age: 35)
person.info()

Output:

My name is Alice and I am 35 years old.

Common data types, such as Int, String, or Double are all implemented as structs behind the scenes.

Next, you are going to learn how to use classes to create custom types when structs are not enough.

Next chapter: Classes in Swift

Share

Share on twitter
Share on linkedin
Share on facebook
Share on pinterest
Share on email