struct ExampleUse a struct, and review the difference between structs and classes.
This page was last reviewed on Aug 23, 2023.
Struct. 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.
Struct versus 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.
Here We create a tiny class (TestClass) and a tiny struct (TestStruct). We pass them both to methods, as arguments.
Note The TestClass reference is copied, but not the data of the class. So we can change the class's inner data.
Note 2 A 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
Selecting structs. 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.
However For most custom types, classes are better. Structs have both performance advantages and negatives.
And When we pass a struct to a func, all its data is copied. This can be faster (if the struct is small) or slower (if it is big).
Review. Structs have limitations. They are copied by value, so changes are disallowed or not reflected in the original variable. But structs can reduce allocations.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 23, 2023 (edit).
© 2007-2023 Sam Allen.