Swift Structs and Classes
Structs and classes let you create your own types that group data and actions together.
Structs
A struct groups related properties and methods. Swift gives every struct a free initializer, called the memberwise initializer.
Example
struct Student {
var name: String
var marks: Int
func report() -> String {
marks >= 50 ? "\(name) passed" : "\(name) needs a retake"
}
}
let ali = Student(name: "Ali", marks: 82)
let zara = Student(name: "Zara", marks: 41)
print(ali.report())
print(zara.report())
print(ali.name)Ali passed Zara needs a retake Ali
Mutating Methods
A struct method cannot change the struct's properties unless it is marked mutating. The struct must also be stored in a var.
Example
struct Wallet {
var balance: Int
mutating func spend(_ amount: Int) {
if amount <= balance {
balance -= amount
} else {
print("Not enough money")
}
}
}
var myWallet = Wallet(balance: 500)
myWallet.spend(200)
myWallet.spend(400)
print(myWallet.balance)Not enough money 300
Classes
A class is like a struct, but it has no free initializer, so you write init yourself. Classes can also inherit from other classes.
Example
class Vehicle {
var name: String
init(name: String) {
self.name = name
}
func describe() -> String {
"\(name) is a vehicle"
}
}
class Bike: Vehicle {
override func describe() -> String {
"\(name) has two wheels"
}
}
let car = Vehicle(name: "Suzuki Mehran")
let bike = Bike(name: "Honda 125")
print(car.describe())
print(bike.describe())Suzuki Mehran is a vehicle Honda 125 has two wheels
self.namemeans "the property of this object", to tell it apart from the parametername.overridereplaces a method from the parent class.
Value Types and Reference Types
This is the most important difference between the two:
- A struct is a value type. Assigning it to a new variable makes a copy.
- A class is a reference type. Assigning it shares the same object.
Example
struct PointS { var x = 0 }
class PointC { var x = 0 }
var s1 = PointS()
var s2 = s1
s2.x = 10
print(s1.x, s2.x)
let c1 = PointC()
let c2 = c1
c2.x = 10
print(c1.x, c2.x)0 10 10 10
Changing s2 did not change s1, because s2 is a copy. Changing c2 also changed c1, because both names point to the same object.
Struct or Class?
| Feature | Struct | Class |
|---|---|---|
| Type | Value (copied) | Reference (shared) |
| Free initializer | Yes | No |
| Inheritance | No | Yes |
| Changing properties in methods | Needs mutating | Allowed |
Apple recommends using a struct by default. Choose a class when you need inheritance or when many parts of your app must share one object.
Computed Properties
A computed property calculates its value every time you read it:
Example
struct Rectangle {
var width: Double
var height: Double
var area: Double { width * height }
}
let room = Rectangle(width: 12, height: 10)
print(room.area)120.0
Exercise
Exercise
What is printed? struct Box { var n = 1 } var a = Box() var b = a b.n = 5 print(a.n)
