Home > Software engineering >  Why this Swift enumeration example in the GuideTour using switch on variable with only one value?
Why this Swift enumeration example in the GuideTour using switch on variable with only one value?

Time:07-25

This piece of code of GuideTour

enum ServerResponse {
    case result(String, String)
    case failure(String)
}

let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out of cheese.")

switch success {
case let .result(sunrise, sunset):
    print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
    print("Failure...  \(message)")
}
// Prints "Sunrise is at 6:00 am and sunset is at 8:09 pm."

is extreamly baffling.

Why do we need a switch here?

Because from the sample code, I thought the variable, success is already assigned with one value, which is ServerResponse.result("6:00 am", "8:09 pm").

And using a switch on a variable with just one value is kind of strange...

CodePudding user response:

Yes. The example is confusing. They're demonstrating how switch can be used to extract the associated values of the enum.

A better example would have been:

enum ServerResponse {
    case success(String, String)
    case failure(String)
}

let success = ServerResponse.success("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out of cheese.")

let result = Bool.random() ? success : failure

switch result {
case let .success(sunrise, sunset):
    print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
    print("Failure...  \(message)")
}

Then each time you run the code, you might get the .success or .failure result. In either case, the switch extracts the values associated with the enum value and uses them to print.


Besides using switch, the other way to extract associated values of an enum is case let:

if case let .success(sunrise, sunset) = result {
    print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
}

This line says that if the assignment of result to the pattern .success(sunrise, sunset) succeeds, then print using the extracted values. If the result were a .failure, then the print would be skipped.

CodePudding user response:

If you check the type of success, you will see that it is ServerResponse so as failure is. That means, when you switch success or failure, you have to handle all cases from ServerResponse enum.

Above code could be written

let success: ServerResponse = .result("6:00 am", "8:09 pm")
let failure: ServerResponse = .failure("Out of cheese.")

switch success {
case let .result(sunrise, sunset):
    print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
    print("Failure...  \(message)")
}
  • Related