Swift Tutorial menu

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

swift
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)
Output
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

swift
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)
Output
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

swift
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())
Output
Suzuki Mehran is a vehicle
Honda 125 has two wheels
  • self.name means "the property of this object", to tell it apart from the parameter name.
  • override replaces 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

swift
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)
Output
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?

FeatureStructClass
TypeValue (copied)Reference (shared)
Free initializerYesNo
InheritanceNoYes
Changing properties in methodsNeeds mutatingAllowed

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

swift
struct Rectangle {
    var width: Double
    var height: Double
    var area: Double { width * height }
}

let room = Rectangle(width: 12, height: 10)
print(room.area)
Output
120.0

Exercise

Exercise

What is printed? struct Box { var n = 1 } var a = Box() var b = a b.n = 5 print(a.n)

Learn Swift with a teacher

Join the App Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp