Swift Structs
A structure (struct) groups related values into one new type. Structs are the workhorse of Swift: Int, String, Array and Dictionary are all structs in the standard library, and Apple recommends reaching for a struct first whenever you model data.
Defining a struct
A struct has properties (the data it stores) and can have methods (functions that belong to it).
struct Book {
var title: String
var author: String
var pages: Int
}
let book = Book(title: "Swift Basics", author: "Mai Linh", pages: 240)
print(book.title)
print("\(book.author) wrote \(book.pages) pages")Swift Basics
Mai Linh wrote 240 pages
Notice that we never wrote an initializer. Swift generates a memberwise initializer automatically, with one labelled parameter per stored property, in declaration order.
Default values
Properties can have default values. The memberwise initializer then makes those parameters optional to pass:
struct Settings {
var volume = 50
var darkMode = false
var language = "en"
}
let a = Settings()
let b = Settings(darkMode: true)
let c = Settings(volume: 80, language: "vi")
print(a.volume, a.darkMode, a.language)
print(b.volume, b.darkMode, b.language)
print(c.volume, c.darkMode, c.language)50 false en
50 true en
80 false vi
Methods and mutating
A method can read the struct's properties freely. But a struct is a value type, and by default its methods may not change self. A method that modifies properties must be marked mutating:
struct Counter {
var count = 0
func describe() -> String {
"Count is \(count)"
}
mutating func increment(by step: Int = 1) {
count += step
}
mutating func reset() {
self = Counter() // a mutating method can even replace self
}
}
var clicks = Counter()
clicks.increment()
clicks.increment(by: 5)
print(clicks.describe())
clicks.reset()
print(clicks.describe())Count is 6
Count is 0
let makes the whole struct constant
When a struct instance is stored in a let constant, none of its properties can change — even those declared with var. The compiler catches the mistake:
struct Point {
var x: Int
var y: Int
}
let origin = Point(x: 0, y: 0)
origin.x = 10error: emit-module command failed with exit code 1 (use -v to see invocation)
<source>:7:8: error: cannot assign to property: 'origin' is a 'let' constant
4 | }
5 |
6 | let origin = Point(x: 0, y: 0)
| `- note: change 'let' to 'var' to make it mutable
7 | origin.x = 10
| `- error: cannot assign to property: 'origin' is a 'let' constant
Change let origin to var origin and the program compiles.
Structs are copied
Assigning a struct to another variable, or passing it to a function, makes an independent copy. Changing the copy never affects the original:
struct Score {
var points: Int
}
var mine = Score(points: 10)
var yours = mine // a full copy
yours.points += 5
print("mine:", mine.points)
print("yours:", yours.points)mine: 10
yours: 15
This "value semantics" makes structs easy to reason about: nobody else can change your data behind your back. You will compare it with classes in the Value vs Reference Types lesson.
Structs at a glance
| Feature | Struct |
|---|---|
| Keyword | struct |
| Kind of type | Value type (copied on assignment) |
| Free initializer | Memberwise initializer |
Changing self in a method |
Needs mutating |
| Inheritance | Not supported (use protocols instead) |
| Typical use | Data models: points, settings, records, view state |
Tip: Start with a
struct. Switch to aclassonly when you need shared identity (several parts of the program must see the same object) or inheritance.
Test yourself
What does Swift generate automatically for a struct with no custom initializer?
- A copy constructor
- A memberwise initializer
- A deinitializer
- A
descriptionproperty
Which keyword must a struct method have if it changes a property?
mutatinginoutoverridedynamic
After var b = a; b.x = 5 (where a is a struct), what happens to a.x?
- It becomes 5
- It is unchanged
- The program crashes
- It becomes nil