0
0
Swiftprogramming~5 mins

Why structs are preferred in Swift

Choose your learning style9 modes available
Introduction

Structs are preferred in Swift because they are simple, safe, and efficient. They help keep your code clear and avoid unexpected changes.

When you want to group related values together, like a point with x and y coordinates.
When you want to create small, simple data containers that won't change unexpectedly.
When you want to avoid bugs caused by shared data changes in multiple places.
When you want your data to be copied automatically instead of shared.
When you want better performance for small data types.
Syntax
Swift
struct StructName {
    var property1: Type
    var property2: Type
    // more properties or methods
}

Structs automatically get a memberwise initializer to create new instances easily.

Structs are value types, so they are copied when assigned or passed around.

Examples
This struct groups two integer values to represent a point in 2D space.
Swift
struct Point {
    var x: Int
    var y: Int
}
Shows that changing p2 does not affect p1 because structs are copied.
Swift
var p1 = Point(x: 3, y: 4)
var p2 = p1
p2.x = 10
print(p1.x) // prints 3
print(p2.x) // prints 10
Sample Program

This program shows how changing rect2 does not change rect1 because Rectangle is a struct and copied on assignment.

Swift
struct Rectangle {
    var width: Int
    var height: Int

    func area() -> Int {
        return width * height
    }
}

var rect1 = Rectangle(width: 5, height: 10)
var rect2 = rect1
rect2.width = 20

print("rect1 width: \(rect1.width), area: \(rect1.area())")
print("rect2 width: \(rect2.width), area: \(rect2.area())")
OutputSuccess
Important Notes

Structs are copied on assignment, so changes to one copy do not affect others.

Classes are reference types and share data, which can cause unexpected bugs if not careful.

Use structs for simple data and classes when you need shared, mutable state.

Summary

Structs are simple and safe because they copy data instead of sharing it.

They help avoid bugs caused by unexpected changes in shared data.

Swift prefers structs for small, simple data types for better performance and clarity.