Junior — Middle
What is the main difference between a class and a structure in programming languages?
sobes.tech AI
Answer from AI
The main difference between class and struct in programming languages like Swift or C# is that a class is a reference type, while a struct is a value type.
- Class (class): class objects are stored on the heap, and when assigned or passed, a reference to the object is copied. Changes through one reference are reflected in others.
- Struct (struct): when assigned or passed, a copy of the data is created. Changes in the copy do not affect the original.
For example, in Swift:
struct Point {
var x: Int
var y: Int
}
class Circle {
var center: Point
var radius: Double
init(center: Point, radius: Double) {
self.center = center
self.radius = radius
}
}
Here, Point is a struct, and copying it creates a new independent instance, while Circle is a class, and its objects are passed by reference.