Structures and Classes
Structures and classes allow you to create custom types that bundle data and behavior.
Similarities
Both can:
- Store values in properties
- Define methods for functionality
- Use subscripts for value access
- Set initial state with initializers
- Be extended for added features
- Conform to protocols for standard behavior
Differences: Classes Only
Classes offer extras that structures lack:
- Inheritance from other classes
- Runtime type casting
- Deinitializers for cleanup
- Reference counting for shared instances
Tip: Use structures by default for simplicity; opt for classes when needed.
Definition Syntax
Use struct for structures and class for classes:
swift
struct Point {
var x = 0
var y = 0
}
class Person {
var name: String = "Unknown"
var age = 0
}Naming: Types in UpperCamelCase; properties/methods in lowerCamelCase.
Instances
Create with parentheses:
swift
let origin = Point()
var teacher = Person()Property Access
Use dot syntax:
swift
print("Point at (\(origin.x), \(origin.y))") // Point at (0, 0)
teacher.name = "Alice"
teacher.age = 28
print("\(teacher.name), age \(teacher.age)") // Alice, age 28Memberwise Initializers (Structures)
Structures get them automatically:
swift
let customPoint = Point(x: 5, y: 10)Classes do not.
Value Types: Structures and Enumerations
Value types copy on assignment:
swift
var p1 = Point(x: 3, y: 4)
var p2 = p1 // Copy made
p2.x = 7
print(p1.x) // 3
print(p2.x) // 7Enum example:
swift
enum Direction {
case up, down, left, right
mutating func turnLeft() {
switch self {
case .up: self = .left
case .left: self = .down
case .down: self = .right
case .right: self = .up
}
}
}
var heading = Direction.right
let savedHeading = heading
heading.turnLeft()
print(heading) // up
print(savedHeading) // rightReference Types: Classes
Classes share instances:
swift
let employee1 = Person()
employee1.name = "Bob"
employee1.age = 30
let employee2 = employee1 // Same instance
employee2.age = 31
print(employee1.age) // 31
print(employee2.age) // 31Identity Check (Classes)
Use === / !==:
swift
if employee1 === employee2 {
print("Same instance")
} // Same instance=== checks identity; == checks equality (implement if needed).
Summary Table
| Aspect | Structure | Class |
|---|---|---|
| Type | Value | Reference |
| On Assignment | Copied | Shared |
| Initializer | Memberwise | Custom |
| Inheritance | No | Yes |
| Deinitializers | No | Yes |
Prefer: Structures for most cases.