Structures, commonly known as structs, are fundamental building blocks in Swift programming. They allow developers to create custom, value-type data types that encapsulate related properties and methods.
A structure in Swift is a value type that can store multiple related properties and define methods to provide functionality. Unlike classes, structs are copied when passed around, making them ideal for representing simple data types.
To define a structure in Swift, use the struct
keyword followed by the structure name. Here's a basic example:
struct Person {
var name: String
var age: Int
}
This creates a Person
struct with two properties: name
and age
.
Once defined, you can create instances of your structure and access its properties:
let john = Person(name: "John Doe", age: 30)
print(john.name) // Output: John Doe
print(john.age) // Output: 30
Structures can also contain methods to perform actions or computations. Here's an example:
struct Rectangle {
var width: Double
var height: Double
func area() -> Double {
return width * height
}
}
You can then use this method on an instance of the structure:
let rect = Rectangle(width: 5.0, height: 3.0)
print(rect.area()) // Output: 15.0
By default, methods in structures cannot modify the structure's properties. To allow modification, use the mutating
keyword:
struct Counter {
var count = 0
mutating func increment() {
count += 1
}
}
Consider using structures when:
To further enhance your understanding of Swift structures, explore these related topics:
By mastering Swift structures, you'll be able to create efficient, thread-safe, and easy-to-use custom types in your Swift applications.