AnyCompiler

Structs and Classes

Swift gives you two ways to define a custom type: struct and class. The difference is the same value-versus-reference distinction C# draws with struct versus class — but where C# treats struct as an occasional opt-in, Swift's own standard library types (String, Array, Dictionary, Int) are all structs, and Swift's own style guides recommend struct as your default choice, reaching for class only when you specifically need reference semantics or inheritance.

struct Point {
    var x: Int
    var y: Int
}
class Box {
    var value: Int
    init(value: Int) {
        self.value = value
    }
}
func modifyPoint(_ p: Point) {
    var copy = p
    copy.x = 100
}
func modifyBox(_ b: Box) {
    b.value = 100
}
var p1 = Point(x: 1, y: 2)
modifyPoint(p1)
print(p1.x)

let b1 = Box(value: 1)
modifyBox(b1)
print(b1.value)
Output
1
100

modifyPoint(p1) only ever touches its own local copy — p1 itself never changes, so it still prints 1. modifyBox(b1) instead receives a reference to the same Box, so the change is visible afterward: 100. Note that Point didn't need an explicit init — structs get a free, automatic initializer from their stored properties, while Box (a class) needed one written out by hand.

Next: mutating methods — why a struct's own methods can't change its properties by default, and the real compile error you get from forgetting the fix.

Practice exercise

Define a struct named Point with var x: Int and var y: Int. Create let p = Point(x: 3, y: 4) and print "3,4" using p.x and p.y.