How does one access the switch statement result of the example apple swift book code?
I guess I could make function that just returns the value of the case statement but I am trying to understand this code.
enum ServerResponse {
case Result(String, String)
case Error(String)
}
let success = ServerResponse.Result("6:00 am", "8:09 pm")
let failure = ServerResponse.Error("Out of cheese.")
switch success {
case let .Result(sunrise, sunset):
let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
case let .Error(error):
let serverResponse = "Failure... \(error)"
}
The example is so contrived that it's not at all helpful. Consider this
enum ServerResponse {
case Result(String, String)
case Error(String)
}
for i in 1...100 {
let mySuccess: ServerResponse = {
let zeroOrOne = rand() % 2
if zeroOrOne == 0 {
return ServerResponse.Result("7:00 am", "8.09 pm")
} else {
return ServerResponse.Error("Out of cheese.")
}
}()
var serverResponse: String
switch mySuccess {
case let .Result(sunrise, sunset):
serverResponse = "Sunrise is at \(sunrise) and sunset as \(sunset)"
case let .Error(error):
serverResponse = "Failure... \(error)"
}
println(serverResponse)
}
The gist is that the 'success' variable in the example should really be an assignment as a result of some function / subsystem call. I wrapped it in a loop for println() clarity
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments