Struct are similar to classes but have distinct features and are often preferred in value-oriented programming.
Features
- Value Types: Structures are value types, meaning instances are copied when passed around.
- Custom Initializers: Swift provides a default initializer, but you can define your own.
- Properties and Methods: Structures can have stored and computed properties, as well as methods.
- Immutability with
let
: If a structure instance is declared withlet
, all its properties become immutable. - Protocols: Structures can adopt and conform to protocols.
- No Inheritance: Unlike classes, structures do not support inheritance.
struct Rectangle {
var length: Double
var width: Double
func area() -> Double {
return length * width
}
}
var rect = Rectangle(length: 10.0, width: 5.0)
print("Area of rectangle: \(rect.area())")
// Output: 50.0
Mutating Methods
To modify a structure’s properties within a method, you need to mark the method as mutating
struct Counter {
var count: Int = 0
mutating func increment() {
count += 1
}
mutating func reset() {
count = 0
}
}
var counter = Counter()
counter.increment()
print("Count: \(counter.count)") // Output: Count: 1
counter.reset()
print("Count: \(counter.count)") // Output: Count: 0
Use Cases of Structs
- Data Models: Structures are ideal for representing simple data models like coordinates, dimensions, and configurations.
- Immutable Entities: Use structures when you need value semantics and immutability.
- Lightweight Objects: They are more efficient for small, lightweight objects compared to classes.
// Define a struct
struct PersonStruct {
var name: String
var age: Int
}
var structPerson1 = PersonStruct(name: "Bishal", age: 25)
var structPerson2 = structPerson1 // Copies the values
// Modify structPerson2
structPerson2.name = "Ram"
print("Struct Person 1: \(structPerson1.name), Age: \(structPerson1.age)") //Output: Bishal, 25
print("Struct Person 2: \(structPerson2.name), Age: \(structPerson2.age)") //Output: Ram, 25