# Swift Structures

> Learn how structures work in Swift, from defining stored properties and methods to why structs are value types that get copied when passed around.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2021-06-09 | Topics: [Swift](https://flaviocopes.com/tags/swift/) | Canonical: https://flaviocopes.com/swift-structures/

> This tutorial belongs to the [Swift](https://flaviocopes.com/swift-introduction/) 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:

```swift
struct Dog {

}
```

Inside a structure you can define **stored properties**:

```swift
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:

```swift
let roger = Dog()
```

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

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

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

```swift
roger.age = 9
```

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

```swift
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.

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

And we also have **type methods**:

```swift
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.
