Skip to content
AgileLogics
6 min read

Structs

Prerequisites: Functions, Closures

A struct (structure) defines your own type by grouping related values and the functions that work on them. Structs are the most common way to model data in Swift — String, Int, Array, and Dictionary are all structs themselves.

Real-world analogy: a struct is a form template — "Name, Email, Age". Each filled-in form is an instance of that template.

Syntax

struct TypeName {
    var property: Type
    func method() { }
}

Example

struct User {
    let name: String
    var age: Int

    func describe() -> String {
        "\(name) is \(age) years old"
    }
}

var ada = User(name: "Ada", age: 36)
print(ada.describe())

ada.age += 1
print(ada.age)
print(ada)

Expected output

Ada is 36 years old
37
User(name: "Ada", age: 37)

Line by line:

  • let name and var age are properties — values stored in every User. name can't change after creation; age can.
  • describe() is a method — a function that belongs to the type and can read its properties.
  • User(name:age:) is created automatically. Swift gives every struct a memberwise initializer with one parameter per property.
  • Printing a struct shows its type and every property — handy while learning and debugging.

Because ada is a var, its var properties can be changed. If you declare an instance with let, none of its properties can change, even the var ones.

Common mistakes

  • Declaring an instance with let and then changing a property: cannot assign to property: 'ada' is a 'let' constant.
  • Using UpperCamelCase for properties or lowerCamelCase for the type. Types are User; properties are firstName.

Practice

Define a Book struct with a title, an author, and a pages count, plus a method isLong() that returns true for more than 300 pages. Create one book and print the result.

Show solution
struct Book {
    let title: String
    let author: String
    let pages: Int

    func isLong() -> Bool {
        pages > 300
    }
}

let book = Book(title: "Dune", author: "Frank Herbert", pages: 412)
print(book.isLong())
true