Lesson 55Structs

Value Types

Value Types Explained

Structs are value types - when you assign a struct to a new variable, a copy is made!

Value vs Reference

Value Types (Struct)

Creates independent copies

Reference Types (Class)

Shares the same instance

Benefits of Value Types

Predictable behavior - no surprises
Thread safety - safe in concurrent code
No shared state bugs
Easier to understand and debug

Built-in Value Types

StringIntDoubleArrayDictionary
main.swift
// VALUE TYPES VS REFERENCE TYPES
// Structs are VALUE TYPES - they are COPIED when assigned

// VALUE TYPE BEHAVIOR
struct Point {
    var x: Int
    var y: Int
}

var point1 = Point(x: 10, y: 20)
var point2 = point1  // Creates a COPY

point2.x = 100  // Only changes point2

print(point1.x)  // 10 (unchanged!)
print(point2.x)  // 100

// COPY DEMONSTRATION
struct Person {
    var name: String
    var age: Int
}

var alice = Person(name: "Alice", age: 25)
var aliceCopy = alice  // Independent copy

aliceCopy.name = "Alice Clone"
print(alice.name)      // Alice
print(aliceCopy.name)  // Alice Clone

// COPY-ON-WRITE (Optimization)
var array1 = [1, 2, 3, 4, 5]
var array2 = array1  // No actual copy yet

array2.append(6)  // NOW it copies
print(array1)  // [1, 2, 3, 4, 5]
print(array2)  // [1, 2, 3, 4, 5, 6]

// PASSING TO FUNCTIONS
struct Counter {
    var value: Int = 0
}

func printCounter(_ counter: Counter) {
    print("Counter: \(counter.value)")  // copy
}

func incrementCounter(_ counter: inout Counter) {
    counter.value += 1  // inout allows modification
}

var myCounter = Counter()
incrementCounter(&myCounter)
print(myCounter.value)  // 1

// BENEFITS OF VALUE TYPES
// 1. Predictable behavior
// 2. Thread safety
// 3. No shared state bugs
// 4. Easier to reason about

// BUILT-IN VALUE TYPES
let string: String = "Hello"
let number: Int = 42
let decimal: Double = 3.14
let array: [Int] = [1, 2, 3]
let dict: [String: Int] = ["a": 1]
// All are structs (value types)!

// COMPARING WITH ==
struct Size: Equatable {
    var width: Double
    var height: Double
}

let size1 = Size(width: 100, height: 50)
let size2 = Size(width: 100, height: 50)
print(size1 == size2)  // true (same values)

Try It Yourself!

Create two Point structs, assign one to another, modify the copy, and verify the original is unchanged!