Swift Structures

This tutorial belongs to the Swift series

Structures are one essential Swift concepts.

Structures are everywhere in Swift. Even the built-in types are structures.

We can create instances of structures, which we call objects.

In most languages, objects can only be created from classes. Swift has classes, too, but you can create objects also from structures and the official documentation advises to prefer structures because they are easier to use.

They are a light versions of classes.

A struct can have properties. A struct can have methods (functions) A struct can define subscripts A struct can define initializers A struct can conform to protocols A struct can be extended

One important thing classes allow is inheritance, so if you need that, you have classes.

A struct is defined using this syntax:

struct Dog {

}

Inside a structure you can define stored properties:

struct Dog {
    var age = 8
    var name = "Roger"
}

This structure definition defines a type. To create a new instance with this type, we use this syntax:

let roger = Dog()

Once you have an instance, you can access its properties using the dot syntax:

let roger = Dog()
roger.age
roger.name

The same dot syntax is used to update a property value:

roger.age = 9

You can also create a struct instance passing the values of the properties:

let syd = Dog(age: 7, name: "Syd")
syd.age
syd.name

To do so, properties must be defined variables, with var, not as constants (with let). It’s also important to respect the order those properties are defined.

Structures can have instance methods: functions that belong to an instance of a structure.

struct Dog {
    var age = 8
    var name = "Roger"
    func bark() {
        print("\(name): wof!")
    }
}

And we also have type methods:

struct Dog {
    var age = 8
    var name = "Roger"
    func bark() {
        print("\(name): wof!")
    }
    static func hello() {
        print("Hello I am the Dog struct")
    }
}

Invoked as Dog.hello()

Structures are a value type. This means they are copied when passed to a function, or when returned from a function. And when we assign a variable pointing to a structure to another variable.

This also means that if we want to update the properties of a structure we must define it using var and not let.

All types in Swift are defined as structures: Int, Double, String, arrays and dictionaries, and more, are structures.

⭐️ Join the waiting list for the JavaScript Masterclass ⭐️