Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Confusion about Swift enumeration example in the GuideTour

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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…

>Solution :

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.


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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading