Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Peter Fuhrey
2,146 PointsElaboration on a switch statement for a enum
Hi, so I just recently completed the associated values section of the Swift course and I feel as though the associated values itself is pretty easy to grasp however I'm kinda lost as to what exactly the switch statement is performing on this enum. I get that it's unwrapping the value of .Failure I guess I'm just sort of mixed up on the syntax of the actual switch statement. I'm sorry if this is vague but if someone had the time I'd appreciate a little step by step as to how the switch statement is operating.
enum Status {
case Success(String)
case Failure(String)
}
let downloadStatus = Status.Failure("Network Connection Lost")
switch downloadStatus {
case .Success(let success):
println(success)
case .Failure(let failure):
println(failure)
}
1 Answer
Chris Shaw
26,676 PointsHi Peter,
The switch statement in your above code is actually very simple but the syntax has confused a few other users because of the sudden ability to pass and receive string values via the case statements. To clear up any confusion we can write the same switch using the below code without breaking it.
switch downloadStatus {
case .Success:
println("Looking good!")
case .Failure:
println("Something went wrong!")
}
The only difference here is instead of assigning the string values via a constant we're simply checking if downloadStatus matches one of our enum values, Swift has no requirement for us to always request the enum value which would be cumbersome and create ugly code very quickly.
Back to your original code, as I said above this code will execute the same way, the only difference is we're assigning a constant using the string value set when we constructed the enum, one thing that users also get confused by is the naming conventions around this and the secret is you can call them whatever you want as seen below.
switch downloadStatus {
case .Success(let itWasSuccessful):
println(itWasSuccessful)
case .Failure(let somethingFailed):
println(somethingFailed)
}
Hope that helps.
Peter Fuhrey
2,146 PointsPeter Fuhrey
2,146 PointsYes! Thank you! I guess it was just that constant throwing me off!