SWIFT
Swift Class: Syntax, Usage, and Examples
A Swift class is a reference type that lets you define reusable blueprints for objects. Unlike structs, classes support inheritance and reference semantics, making them ideal for managing shared data and complex object hierarchies.
How to Use Classes in Swift
A class is defined using the class
keyword, followed by properties and methods inside curly braces.
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func describe() -> String {
return "\(name) is \(age) years old."
}
}
Creating and Initializing a Class
You create an instance of a class using init
, which is called automatically when a new object is created.
let person = Person(name: "Alice", age: 30)
print(person.describe()) // Output: Alice is 30 years old.
Since classes are reference types, modifying a copied instance affects the original object.
Mutating Class Properties
Unlike structs, class properties can be changed without marking methods as mutating
.
person.age = 31
print(person.describe()) // Output: Alice is 31 years old.
When to Use Classes in Swift
Classes are useful when you need to manage shared data or create complex object-oriented models.
Implementing Object-Oriented Design
Classes allow you to define objects with behavior and relationships.
class Car {
var model: String
var speed: Int = 0
init(model: String) {
self.model = model
}
func accelerate() {
speed += 10
}
}
let car = Car(model: "Tesla")
car.accelerate()
print(car.speed) // Output: 10
Using Inheritance
A class can inherit properties and methods from another class, making it easy to share behavior.
class ElectricCar: Car {
var batteryLevel: Int = 100
func charge() {
batteryLevel = 100
}
}
let myCar = ElectricCar(model: "Tesla Model 3")
print(myCar.batteryLevel) // Output: 100
Managing Reference Semantics
Since classes use reference semantics, they are ideal for managing mutable shared state.
class Counter {
var count = 0
}
let counter1 = Counter()
let counter2 = counter1
counter2.count += 1
print(counter1.count) // Output: 1
Both counter1
and counter2
point to the same object, so modifying one affects the other.
Examples of Classes in Swift
Defining Methods and Computed Properties
A class can include methods and computed properties that dynamically generate values.
class Rectangle {
var width: Double
var height: Double
init(width: Double, height: Double) {
self.width = width
self.height = height
}
var area: Double {
return width * height
}
}
let rect = Rectangle(width: 5, height: 10)
print(rect.area) // Output: 50
Overriding Methods
A subclass can override methods from a parent class to provide custom behavior.
class Animal {
func makeSound() {
print("Some generic animal sound")
}
}
class Dog: Animal {
override func makeSound() {
print("Woof!")
}
}
let myDog = Dog()
myDog.makeSound() // Output: Woof!
Comparing Classes to Structs
Structs and classes behave differently when copied.
struct UserStruct {
var name: String
}
class UserClass {
var name: String
init(name: String) {
self.name = name
}
}
var structUser1 = UserStruct(name: "Emily")
var structUser2 = structUser1
structUser2.name = "Sophia"
print(structUser1.name) // Output: Emily
var classUser1 = UserClass(name: "Emily")
var classUser2 = classUser1
classUser2.name = "Sophia"
print(classUser1.name) // Output: Sophia
Structs create independent copies, while classes maintain a single reference.
Learn More About Classes in Swift
Swift classes support additional features like protocols, abstract classes, and type checking.
Using Protocols with Classes
A class can conform to a protocol, enforcing a specific set of methods and properties.
protocol Drivable {
func drive()
}
class Bicycle: Drivable {
func drive() {
print("Pedaling forward")
}
}
let bike = Bicycle()
bike.drive() // Output: Pedaling forward
Creating an Abstract Class
Swift does not support abstract classes, but you can achieve a similar effect using a base class with methods marked as fatalError()
.
class Shape {
func area() -> Double {
fatalError("Subclasses must implement this method")
}
}
class Square: Shape {
var side: Double
init(side: Double) {
self.side = side
}
override func area() -> Double {
return side * side
}
}
let square = Square(side: 4)
print(square.area()) // Output: 16
Checking Class Type at Runtime
You can check if an instance belongs to a specific class type using is
and as?
.
let objects: [Any] = [Square(side: 4), Bicycle()]
for object in objects {
if let shape = object as? Shape {
print("This is a shape with area: \(shape.area())")
} else {
print("This is not a shape")
}
}
Defining Class Functions
Class functions operate at the class level rather than the instance level.
class MathUtility {
class func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
}
print(MathUtility.add(3, 5)) // Output: 8
Using Class Properties
A class can have properties shared across all instances using static
or class
.
class Configuration {
static let apiEndpoint = "https://api.example.com"
}
print(Configuration.apiEndpoint) // Output: https://api.example.com
Best Practices for Using Classes
- Use classes when you need reference semantics to share mutable state.
- Prefer structs for lightweight data models that do not require inheritance.
- Use protocols to define reusable behavior that multiple classes can conform to.
- Avoid deep inheritance hierarchies, as they can make code hard to maintain.
- Use
final
on classes that should not be subclassed to improve performance.
Swift classes provide powerful tools for structuring your code, making it flexible and reusable. They work well for managing objects that need to maintain shared state or extend functionality through inheritance.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.