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.
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