Introduction
Structs hold their own copy of data. When you assign or pass them, you get a fresh copy, not a shared one.
Structs hold their own copy of data. When you assign or pass them, you get a fresh copy, not a shared one.
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.
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
struct Counter { var count: Int } var c1 = Counter(count: 1) var c2 = c1 c2.count += 1 print(c1.count) // 1 print(c2.count) // 2
This shows that changing book2's pages does not affect book1 because structs copy on assign.
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)")
Structs are copied when assigned or passed to functions.
This behavior helps avoid bugs from shared data changes.
Structs hold their own copy of data.
Assigning a struct copies its data, not just a reference.
Changing one copy does not affect others.
struct followed by the name and braces containing properties.struct Person { var name: String }. Using = after the name is invalid, using class defines a class instead of a struct, and adding parentheses like Person() is incorrect.struct Point { var x: Int; var y: Int }
var p1 = Point(x: 5, y: 10)
var p2 = p1
p2.x = 20
print(p1.x)p1 to p2 copies the data, so p2 is a separate copy.p2.x to 20 does not affect p1.x, which remains 5.struct Counter { var count: Int }
func increment(counter: Counter) {
var counter = counter
counter.count += 1
}
var c = Counter(count: 0)
increment(counter: c)
print(c.count)c.c outside remains unchanged.mutating.Pass the test and this pattern moves unknown