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 nameandvar ageare properties — values stored in everyUser.namecan't change after creation;agecan.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
letand then changing a property:cannot assign to property: 'ada' is a 'let' constant. - Using
UpperCamelCasefor properties orlowerCamelCasefor the type. Types areUser; properties arefirstName.
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