Site icon CodeWithSwift

Struct

Struct are similar to classes but have distinct features and are often preferred in value-oriented programming.

Features

  1. Value Types: Structures are value types, meaning instances are copied when passed around.
  2. Custom Initializers: Swift provides a default initializer, but you can define your own.
  3. Properties and Methods: Structures can have stored and computed properties, as well as methods.
  4. Immutability with let: If a structure instance is declared with let, all its properties become immutable.
  5. Protocols: Structures can adopt and conform to protocols.
  6. 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

  1. Data Models: Structures are ideal for representing simple data models like coordinates, dimensions, and configurations.
  2. Immutable Entities: Use structures when you need value semantics and immutability.
  3. 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
Exit mobile version