C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: We create a tiny class (TestClass) and a tiny struct (TestStruct). We pass them both to methods, as arguments.
Class: The class reference is copied, but not the data of the class. So we can change the class's inner data.
Struct: A struct can be passed to a func, but its data cannot be modified in the func. It is a value, not a reference.
Swift program that uses struct, class
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++
}
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(y)
print(y.code)
// Create a struct instance, which cannot be modified.
var x = TestStruct()
x.code = 1
increment(x)
print(x.code)
Output
2
1
However: For most custom types, classes are better. Structs have both performance advantages and negatives.
Performance: 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).