Junior
What is the difference between classes and structures in Swift?
sobes.tech AI
Answer from AI
Classes are reference types, structures are value types.
Main differences:
- Inheritance: Classes support inheritance, structures do not.
- Type Casting: Allows checking and interpreting the type of an instance at runtime.
- Deinitialization: Classes have deinitializers (
deinit) for resource cleanup, structures do not. - Reference Counting: Classes use automatic reference counting (ARC) for memory management. Structures are copied upon passing or assignment (copy-on-write can be used for optimization).
- Mutating methods: Methods that modify the properties of a structure or enumeration instance must be marked with the
mutatingkeyword. This is not required for classes.
Example of creation:
// Structure
struct Point {
var x: Int
var y: Int
}
// Class
class Circle {
var radius: Double
var center: Point
init(radius: Double, center: Point) {
self.radius = radius
self.center = center
}
}
Example of behavior during assignment:
// Structure
var point1 = Point(x: 1, y: 2)
var point2 = point1 // Creates a copy
point2.x = 10
print(point1.x) // Output: 1
// Class
var circle1 = Circle(radius: 5.0, center: Point(x: 0, y: 0))
var circle2 = circle1 // Reference assignment occurs
circle2.radius = 10.0
print(circle1.radius) // Output: 10.0