Sobes.tech
Junior — Middle

Is it necessary to cover all possible enum values in a switch statement in Swift?

sobes.tech AI

Answer from AI

In Swift, if you use a switch statement for a value of an enum type without associated values, the compiler requires you to cover all possible cases of the enum to make the switch exhaustive. This means you must either list all enum cases or add a default branch.

If you do not cover all cases and do not add a default, the code will not compile.

Example:

enum Direction {
    case north, south, east, west
}

func move(_ dir: Direction) {
    switch dir {
    case .north:
        print("Moving north")
    case .south:
        print("Moving south")
    case .east:
        print("Moving east")
    case .west:
        print("Moving west")
    }
}

If you do not want to list all cases, you can add a default:

switch dir {
case .north:
    print("Moving north")
default:
    print("Other direction")
}
Is it necessary to cover all possible enum values in… - sobes.tech