Swift Structures Example

1. Introduction

Structures, commonly referred to as "structs", are one of the basic building blocks of Swift. They are flexible constructs that allow you to define types with properties and methods. One of the primary distinctions between structures and classes in Swift is that structures are value types, while classes are reference types. This means when a structure is assigned to a new constant or variable, or when it's passed to a function, it's actually copied rather than referenced.

2. Source Code Example

// Define a simple structure to represent a 2D point
struct Point {
    var x: Double
    var y: Double

    // Method to move the point by a delta
    mutating func moveBy(x deltaX: Double, y deltaY: Double) {
        x += deltaX
        y += deltaY

// Create an instance of the Point structure
var initialPoint = Point(x: 3.0, y: 4.0)
print("Initial point is at (\(initialPoint.x), \(initialPoint.y))")

// Modify the point using the moveBy method
initialPoint.moveBy(x: 2.0, y: 3.0)
print("After moving, point is at (\(initialPoint.x), \(initialPoint.y))")

// Copy the value of initialPoint to another variable
let anotherPoint = initialPoint
print("Another point is at (\(anotherPoint.x), \(anotherPoint.y))")

// Demonstrating that structs are value types
var thirdPoint = initialPoint
thirdPoint.moveBy(x: 1.0, y: 1.0)
print("Third point after moving is at (\(thirdPoint.x), \(thirdPoint.y))")
print("Initial point is still at (\(initialPoint.x), \(initialPoint.y))")


Initial point is at (3.0, 4.0)
After moving, point is at (5.0, 7.0)
Another point is at (5.0, 7.0)
Third point after moving is at (6.0, 8.0)
Initial point is still at (5.0, 7.0)

3. Step By Step Explanation

1. We start by defining a Point struct with two properties: x and y. This struct also includes a mutating method moveBy which allows us to change the position of the point by a certain delta.

2. We then create an instance of this struct, initialPoint, and print its position.

3. We demonstrate the moveBy method by moving the initialPoint.

4. To show that structs are value types, we assign the initialPoint to another constant anotherPoint. Since structs are value types, the value is copied over rather than referenced.

5. Lastly, we assign initialPoint to a thirdPoint variable and modify thirdPoint. As seen in the output, the modifications to thirdPoint do not affect initialPoint, underlining the point that structures are indeed value types in Swift.