SyntaxStudy
Sign Up
Swift Beginner 1 min read

Enumerations

Swift enumerations are first-class types with methods, computed properties, and associated values. They are far more powerful than C enums. Associated values let each enum case carry additional typed data. This is a common pattern for representing different states or results that carry different payloads. Raw value enums assign a default value (Int, String, etc.) to each case, useful for mapping to database values or API responses.
Example
// Basic enum
enum Direction {
    case north, south, east, west
}
let heading = Direction.north

// Enum with raw values
enum Planet: Int {
    case mercury = 1, venus, earth, mars
}
let earth = Planet(rawValue: 3)  // Optional<Planet>

// Enum with associated values
enum Result<T> {
    case success(T)
    case failure(Error)
}

enum NetworkError: Error {
    case notFound(url: String)
    case serverError(code: Int, message: String)
    case timeout
}

// Pattern matching with switch
func handleError(_ error: NetworkError) -> String {
    switch error {
    case .notFound(let url):
        return "Not found: \(url)"
    case .serverError(let code, let msg):
        return "Error \(code): \(msg)"
    case .timeout:
        return "Request timed out"
    }
}

let err = NetworkError.serverError(code: 500, message: "Internal error")
print(handleError(err))