0
0
Swiftprogramming~5 mins

Structs are value types (copy on assign) in Swift

Choose your learning style9 modes available
Introduction

Structs hold their own copy of data. When you assign or pass them, you get a fresh copy, not a shared one.

When you want to keep data safe from accidental changes.
When you want each variable to have its own independent data.
When you want simple data containers like points or sizes.
When you want to avoid unexpected side effects from shared data.
Syntax
Swift
struct MyStruct {
    var value: Int
}

var a = MyStruct(value: 10)
var b = a  // b is a copy of a
b.value = 20
print(a.value)  // prints 10
print(b.value)  // prints 20

Assigning one struct to another copies all its data.

Changing the copy does not affect the original.

Examples
Changing p2 does not change p1 because Point is a struct (value type).
Swift
struct Point {
    var x: Int
    var y: Int
}

var p1 = Point(x: 5, y: 5)
var p2 = p1
p2.x = 10
print(p1.x)  // 5
print(p2.x)  // 10
Each variable has its own copy of count.
Swift
struct Counter {
    var count: Int
}

var c1 = Counter(count: 1)
var c2 = c1
c2.count += 1
print(c1.count)  // 1
print(c2.count)  // 2
Sample Program

This shows that changing book2's pages does not affect book1 because structs copy on assign.

Swift
struct Book {
    var title: String
    var pages: Int
}

var book1 = Book(title: "Swift Guide", pages: 100)
var book2 = book1
book2.pages = 200

print("book1 pages: \(book1.pages)")
print("book2 pages: \(book2.pages)")
OutputSuccess
Important Notes

Structs are copied when assigned or passed to functions.

This behavior helps avoid bugs from shared data changes.

Summary

Structs hold their own copy of data.

Assigning a struct copies its data, not just a reference.

Changing one copy does not affect others.