Reputation: 14874
As a practical example, suppose I define:
enum Baby {
case Boy (String)
case Girl (String)
}
and then define a variable (or constant) like so:
let baby1 = Baby.Boy("Joe")
Now I want to pass baby1 to a function that returns a string that depends on whether baby1 is a boy or a girl. How do I write that function? Or is there no way to do that?
Upvotes: 1
Views: 65
Reputation: 154513
I know you said not to answer, but this might help:
Using a switch
statement, you can simultaneously detect the case of the enum and extract the String
for use:
enum Baby {
case Boy (String)
case Girl (String)
}
let baby1 = Baby.Boy("Joe")
let baby2 = Baby.Girl("Sue")
func babyDescription(baby: Baby) -> String {
switch(baby) {
case .Boy(let name):
return "A baby boy named \(name)"
case .Girl(let name):
return "A baby girl named \(name)"
}
}
println(babyDescription(baby1)) // "A baby boy named Joe"
println(babyDescription(baby2)) // "A baby girl named Sue"
Upvotes: 2