← Swift tutorial

Swift

Classes & Structs

Swift has both class and struct for bundling data and behaviour together.

Example: a struct

struct Student {
    let name: String
    let track: String
}

let ada = Student(name: "Ada", track: "Frontend")
print("\(ada.name) is studying \(ada.track)")
Ada is studying Frontend

The key difference between the two: a class is a reference type, if you copy a class instance into another variable, both variables point at the exact same underlying object, so changing one changes what the other sees too. A struct is a value type, copies are completely independent, exactly like copying a plain number or string. Apple recommends structs by default, reaching for classes only when you specifically need shared, mutable state across multiple parts of your code, the opposite default from Java or C#, where classes are the only option for this kind of thing at all.

Example
struct Student {
    let name: String
    let track: String
}

let ada = Student(name: "Ada", track: "Frontend")
print("\(ada.name) is studying \(ada.track)")
Output
Ada is studying Frontend
Ready to go further?

These free tutorials are a preview of what a Code Secure Academy cohort covers, project work and all.

Explore our tracks
Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account