Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 146 ยท Structures, Classes and Enums

Structures

Learn Swift structures - stored and computed properties, memberwise initializers, methods, mutating, value semantics, let versus var instances, Equatable and when to choose a struct.

Up to now your data has been simple values (an Int, a String) or collections of them. Real programs need to group related values into one thing: a point has an x and a y, a book has a title, an author and a page count, a temperature reading has a number and a unit. A structure (struct) is how Swift lets you invent such types. You describe the pieces once, and then create as many values of that shape as you like.

Structs are the workhorse of Swift. Int, Double, Bool, String, Array, Dictionary and Optional are all structs in the standard library, and Swift's own guidance is to start with a struct and switch to a class only when you need something that structs cannot do. This lesson covers declaring structs, their properties and methods, the initializers Swift writes for you, the single most important idea (value semantics), and the mutating keyword that goes with it. Classes is the companion lesson that contrasts the two.

Declaring a struct

A struct has a name, written in UpperCamelCase, and a body containing properties (the data) and methods (the behaviour):

Swift A first struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You never wrote an initializer, yet Book(title:author:pages:) worked. Swift generates a memberwise initializer for every struct: one parameter per stored property, in declaration order, with the property names as argument labels. print(dune) also works because Swift can print any struct, listing its properties. Custom String Convertible shows how to control that output.

A value of a struct type is called an instance. You read and write its properties with dot syntax. Note the difference between the two instances above: dune was declared with let, draft with var. We will see in a moment why that matters so much.

Default values and optional properties

Properties can have default values, and properties that may legitimately be missing can be optional. The memberwise initializer adapts: parameters for properties with defaults become optional, and optional var properties default to nil.

Swift Defaults and optionals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Arguments must still appear in declaration order, but you can leave out any that have defaults. Having isDone = false means Swift infers Bool, so the type annotation is optional, just as with ordinary variables (Constants and Variables).

Methods

A function declared inside a struct is a method. Inside it, the properties are available by name, and self (usually omitted) is the instance the method was called on.

Swift Methods on a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

scaled(by:) does not change room; it builds and returns a new rectangle. That style, producing a changed copy, is very common with structs and is easy to reason about because nothing else is affected.

Computed properties

A property does not have to store anything. A computed property calculates its value each time you read it. It looks like a stored property to callers, which keeps the API tidy:

Swift Computed properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Compare this with a method fahrenheit(): the property form says "this is a fact about the value", while a method says "this does some work". Computed properties can also have setters, observers can watch stored ones, and properties can be lazy or static; all of that is in Properties.

Value semantics: assignment makes a copy

This is the idea that defines structs. A struct is a value type: when you assign it to a new variable, or pass it to a function, you get an independent copy. Changing one does not affect the other.

Swift Copies are independent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Every line behaves as if the value were a plain integer. var b = a then b.x = 100 leaves a alone. The function received its own copy; the array holds its own copies too, so changing list[0] does not change a. This "no spooky action at a distance" property makes structs easy to use correctly in concurrent code, in collections, and in tests.

You might worry about the cost of all that copying. In practice it is small: simple structs are tiny and copying is a few machine instructions, and large collections inside a struct use copy-on-write, so the expensive data is shared until one side actually changes it (Collections Overview explained this).

mutating: methods that change the instance

Because assignment copies, Swift is strict about who may change a struct. A method that modifies the struct's own properties must be marked mutating, and it can then be called only on a var:

Swift mutating methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

mutating is a promise printed in the signature: "calling this changes the value". Without it, a method cannot assign to count. Compare what happens when you forget it:

Swift Forgetting mutating (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports error: left side of mutating operator isn't mutable: 'self' is immutable. In a normal method, self is a constant. Add mutating before func and it compiles.

let versus var: the instance decides

The let or var on the instance controls whether its properties can be changed, even when the properties themselves are declared var:

Swift Changing a property of a let instance (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

This stops with error: cannot assign to property: 'origin' is a 'let' constant. For a value type, the whole value is immutable when it is held in a constant. Contrast that with the equivalent for a class instance in Classes: there, a let reference still lets you change the properties of the object it refers to. The same rule explains why function parameters (which are constants) cannot be modified without an inout marker or a local var copy.

Individual stored properties can also be let, which freezes just that piece forever:

Swift let properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

private(set) lets everyone read balance but only the struct change it, a common way to protect a rule such as "the balance only changes through deposit". Access Control goes deeper.

Initializers you write yourself

The memberwise initializer is convenient, but you can write your own init to compute values, validate input or offer alternatives. Inside an initializer every stored property must be set before you finish:

Swift Custom initializers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first initializer normalizes the fraction (lowest terms, sign on the numerator), so every Fraction in the program obeys the same rule. The second delegates to the first with self.init(...), a pattern called initializer delegation. static func gcd belongs to the type itself rather than to an instance, so we call it as Fraction.gcd.

There is a subtle rule to remember: as soon as you define an init inside the struct body, Swift stops providing the memberwise initializer. If you want both, put your custom initializer in an extension:

Swift Keeping the memberwise initializer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

More on initializers, including failable ones that can return nil, is in Initializers.

Structs and equality

Two points with the same coordinates are the same point. Swift gives you that for free if you declare conformance to Equatable, because every stored property is itself Equatable and the compiler can write == for you. Adding Hashable lets structs be set members or dictionary keys, and Comparable needs you to say how to order them (see Equatable, Hashable and Comparable).

Swift Synthesized Equatable and Hashable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

There is no identity here: p and q are different instances in different variables, yet they are equal and interchangeable. That is the nature of a value.

A struct holding a reference

Structs usually contain value types, but a stored property can be a reference to a class instance. The struct is copied, the reference is copied, but the object it points to is shared. This is a place where value semantics quietly breaks:

Swift A shared object inside a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The names are independent copies, but both services write into one shared log. Neither behaviour is wrong; just be aware of it when you mix the two kinds of type. A struct is only fully a value when everything inside it is a value too.

How big is a struct?

A struct stores its properties inline, one after another, with no separate heap object and no reference counting for simple fields. MemoryLayout reports the sizes:

Swift Struct sizes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

A Pixel is exactly three bytes, a Vec2 is two doubles (16 bytes). Arrays of such structs are stored contiguously in memory, which is excellent for speed. This is one reason Swift programmers reach for structs in performance-sensitive code. Memory Layout explains size, stride and alignment.

When to use a struct

Choose a struct when most of these are true:

  • The type is mostly data, and its meaning comes from its values (a point, a color, a price, a date range).
  • Copying it should produce an independent thing.
  • It does not need inheritance or a shared, changing identity.
  • You want the compiler's help: synthesized ==, Hashable and Codable, and no reference cycles.

Choose a class when you need identity (one shared object that many parts of the program refer to), inheritance, or deinitializers. Classes and Value vs. Reference Semantics give the full comparison.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Swift generate automatically for a struct with no initializer written?

    Structs get a memberwise initializer such as Book(title:author:pages:). Parameters for properties that have default values become optional.
  2. 2. After var b = a where a is a struct, you set b.x = 10. What happens to a.x?

    Structs are value types: assignment copies the value, so the two variables never affect each other.
  3. 3. Which keyword must a struct method have if it changes the struct's own properties?

    In a struct method self is a constant unless the method is marked mutating. Mutating methods can be called only on var instances.
  4. 4. let p = Point(x: 0, y: 0) where x is declared var. What does p.x = 5 do?

    For a value type, a let instance is immutable as a whole, even when its properties are declared var.
  5. 5. You add a custom init inside a struct's body. What happens to the memberwise initializer?

    Defining any initializer in the body removes the memberwise one. Put the custom initializer in an extension to keep both.

Summary

  • A struct groups stored properties with methods, computed properties and initializers; Swift writes a memberwise initializer for you.
  • Structs are value types: assignment, argument passing and storing in a collection all make independent copies.
  • Methods that change the instance must be marked mutating and can only be called on a var; a let instance is wholly immutable.
  • Properties can have defaults, be optional, be let, or be private(set).
  • Defining an init in the struct body removes the memberwise one; use an extension to keep both.
  • Conform to Equatable and Hashable and the compiler synthesizes comparison and hashing.
  • A struct that holds a class reference shares that object between copies.
  • Start with a struct; use a class only for identity, inheritance or shared mutable state.

Next: Classes