How to enforce immutability to prevent the modification of values in Swift

1 Answer

0 votes
// Immutable User in Swift (Using let + Struct for True Immutability)

//
// Swift enforces immutability through:
//
// 1. `let` → prevents reassignment of variables
// 2. `struct` → value types; cannot mutate unless declared `var`
// 3. `let` properties inside a struct → fully immutable fields
// 4. No setters → no mutation path
//
// Attempting to modify an immutable struct or its properties
// results in a compile-time error.
//

// Immutable User using a struct with let properties
struct User {
    let id: Int
    let name: String
}

func main() {
    // Immutable user
    let user = User(id: 42, name: "Ella")

    print("ID: \(user.id)")
    print("Name: \(user.name)")

    // Attempt 1: modify id
    // user.id = 100        // ERROR: Cannot assign to property: 'id' is a 'let' constant

    // Attempt 2: modify name
    // user.name = "Lucas"    // ERROR: Cannot assign to property: 'name' is a 'let' constant

    // Attempt 3: reassign user
    // user = User(id: 100, name: "Lucas")   // ERROR: Cannot assign to value: 'user' is a 'let' constant

    // Instead, Swift uses a new instance to represent changes
    let updatedUser = User(id: user.id, name: "Lucas")

    print("Updated Name (new instance): \(updatedUser.name)")
    print("Original Name: \(user.name)")
}

main()



/* 
run:

ID: 42
Name: Ella
Updated Name (new instance): Lucas
Original Name: Ella

*/

 



answered 1 hour ago by avibootz
...