AnyCompiler

Enums

A basic enum is just a set of named cases, but Swift lets each case carry its own associated data too — something a plain Java or C# enum can't do. Below, .circle carries a radius and .square carries a side, and switch extracts whichever value is relevant to the matched case with let.

enum Shape {
    case circle(radius: Double)
    case square(side: Double)
}
func area(_ shape: Shape) -> Double {
    switch shape {
    case .circle(let radius):
        return Double.pi * radius * radius
    case .square(let side):
        return side * side
    }
}
print(area(.circle(radius: 2)))
print(area(.square(side: 3)))
Output
12.566370614359172
9.0

Compare this to the protocols lesson's version of the same idea: a protocol lets any type, anywhere, opt in to a shared interface — an enum instead gives you a closed, fully-known set of cases, each able to carry its own data, which switch can match exhaustively.

Next: closures — Swift's version of lambdas, and chaining filter and map over a collection.

Practice exercise

Define an enum Shape with cases circle(radius: Double) and square(side: Double). Write a function area(_ shape: Shape) -> Double using switch to compute the correct area for each case, then print area(.square(side: 5)).