In Swift 5.8, a struct
is a value type: its data is stored directly in the variable's memory. This gives performance advantages, but also limits the type.
Structs are less often used in custom code than classes. For small units of data (like positions, sizes) structs are effective. They are copied when passed as arguments.
class
Let us explore a key difference between structs and classes. When we create a struct
, it is a value type. When we pass a struct
to a func
, it is copied.
class
(TestClass
) and a tiny struct
(TestStruct
). We pass them both to methods, as arguments.TestClass
reference is copied, but not the data of the class
. So we can change the class
's inner data.struct
(like TestStruct
) can be passed to a func
, but its data cannot be modified in the func
. It is a value, not a reference.class TestClass { var code: Int = 0 } struct TestStruct { var code: Int = 0 } func increment(t: TestClass) { // The class instance is shared, so we can modify the memory. t.code += 1 } func increment(t: TestStruct) { // The struct is copied, so cannot be modified in this func. // A new struct must be created. } // Create a class instance and modify it in a func. var y = TestClass() y.code = 1 increment(t: y) print(y.code) // Create a struct instance, which cannot be modified. var x = TestStruct() x.code = 1 increment(t: x) print(x.code)2 1
It is possible to modify the fields within a struct
in a function call. But we must use the "mutating" keyword on the func
signature.
func
within a struct
called increaseBy
, and it increments the value of the size field.struct
instance, we can modify it by repeatedly calling the increaseBy
function.struct Example { var size = 0 // Part 1: use mutating keyword on func inside struct. mutating func increaseBy(s: Int) { self.size += s } } // Part 2: call mutating func on struct to modify the existing struct. var e = Example(); e.increaseBy(s: 5) print("Size: \(e.size)") e.increaseBy(s: 1) print("Size: \(e.size)")Size: 5 Size: 6
When should we use structs instead of classes? For small units of data, where the fields will not change often after creation, structs are a good choice.
struct
to a func
, all its data is copied. This can be faster (if the struct
is small) or slower (if it is big).Structs have limitations. They are copied by value, so changes are disallowed or not reflected in the original variable. But structs can reduce allocations.