Blog / June 24, 2023 / 3 mins read / By Mahi Garg

Default Statement in Swift

When working with switch statements in Swift, we often encounter situations where we need to handle known cases explicitly. However, there are times when we also want to handle unknown or unexpected cases gracefully. Swift provides us with a powerful tool, the default statement, to manage such scenarios. In this blog post, we’ll explore the default statement in Swift and learn how to effectively handle unknown cases with elegance.

Basic Usage of default

Let’s start with a simple example of a switch statement to determine the day of the week based on a given number:

func getDayOfWeek(_ dayNumber: Int) -> String {
    switch dayNumber {
    case 1:
        return "Sunday"
    case 2:
        return "Monday"
    case 3:
        return "Tuesday"
    case 4:
        return "Wednesday"
    case 5:
        return "Thursday"
    case 6:
        return "Friday"
    case 7:
        return "Saturday"
    default:
        return "Unknown Day" // Handling unknown cases with 'default'
    }
}

let dayNumber = 9
let dayOfWeek = getDayOfWeek(dayNumber)
print("The day of the week is: \(dayOfWeek)")

In this example, we use the default statement to handle the case when the dayNumber does not match any of the specified cases. If dayNumber is not in the range of 1 to 7, the default case is executed, returning Unknown Day.

Handling Enumerations with default

Enums are a powerful feature in Swift, but they can sometimes evolve with new cases added in subsequent versions of your app. To handle future cases gracefully, you can use the default statement in a switch that deals with enum values:

enum Weather {
    case sunny
    case cloudy
    case rainy
    // case snowy // Uncomment this line to see how 'default' handles the new case.
}

func getWeatherDescription(_ weather: Weather) -> String {
    switch weather {
    case .sunny:
        return "It's a sunny day."
    case .cloudy:
        return "Expect some clouds today."
    case .rainy:
        return "Don't forget your umbrella."
    default:
        return "Weather forecast not available." // Handling future cases with 'default'
    }
}

let currentWeather = Weather.snowy
let weatherDescription = getWeatherDescription(currentWeather)
print("Weather forecast: \(weatherDescription)")

In this example, we have an enum Weather representing different weather conditions. If you uncomment the snowy case, the default statement will handle it gracefully as the new case wasn’t explicitly listed in the switch.

default for Optional Binding

Using the default statement with optional binding is another useful technique. Let’s consider an example where we retrieve an element from an array using an index, but the index might be out of bounds:

func getElement(at index: Int, in array: [Int]) -> String {
    guard index >= 0 && index < array.count else {
        return "Index out of bounds." // Handling invalid index with 'default'
    }
    return "Element at index \(index) is \(array[index])."
}

let numbers = [10, 23, 5, 17, 8]
let indexToRetrieve = 10
let element = getElement(at: indexToRetrieve, in: numbers)
print(element)

In this example, the default statement handles the case where the index provided is out of bounds. Instead of causing a crash or unexpected behavior, we provide a helpful message.

The default statement is a powerful tool in Swift, ensuring that your code gracefully handles unknown or unexpected scenarios. It’s particularly useful in switch statements when dealing with enumerations or handling user inputs. By using the default statement effectively, you can enhance the robustness and reliability of your Swift applications.

Remember to use the default statement thoughtfully, considering potential future changes in your code, and provide helpful responses to users to create a seamless and delightful user experience. Happy coding! 🚀

Comments