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
Steven Andrew
10,933 PointsSWIFT: In the example below why must I place (let one) next to .Success for the code to work?
// In the example below why must I place (let failure) next to .Success for the code to work? Why not (let = success) or (success)?
enum Status { case Success(String) case Failure(String) } let downloadStatus = Status.Failure("Network connection unavailable")
switch downloadStatus { case .Success(let success): println(success) case .Failure(let failure): println(failure) }
3 Answers
Cauli Tomaz
12,362 PointsWhen you created your enum you've decided to use a String to describe the Status even further than just Success or Failure
enum Status {
case Success(String), Failure(String)
}
Because of that, you were obliged to declare your status with an accompanying String, a message that further describes your status:
let downloadStatus = Status.Failure("Network connection unavailable")
Following this idea, when you want to retrieve your status, you can retrieve your String. This is your '(let failure)' and '(let success)', but you could name it anything you like.
// prints "Network connection unavailable"
switch downloadStatus {
case .Success(let success): println(success)
case .Failure(let failure): println(failure)
}
But you are not obliged to retrieve the parameter. Take a look:
// prints "Failure"
switch downloadStatus {
case .Success: println("Success")
case .Failure: println("Failure")
}
Full playground code:
enum Status {
case Success(String), Failure(String)
}
let downloadStatus = Status.Failure("Network connection unavailable")
switch downloadStatus {
case .Success(let success): println(success)
case .Failure(let failure): println(failure)
}
switch downloadStatus {
case .Success: println("Success")
case .Failure: println("Failure")
}
Stone Preston
42,016 Pointsthat is the syntax for accessing en enumeration member's associated value within a switch statement.
from the Swift eBook:
You extract each associated value as a constant (with the let prefix) or a variable (with the var prefix) for use within the switch case’s body
case .QRCode(let productCode):
println("QR code: \(productCode).")
}
Steven Andrew
10,933 PointsThanks !