When I have a situation where I already know enum case statement I want to get the associated value of, is there a cleaner way than using a switch statement to pluck out the associated value?
To have to come up with a switch statement, provide multiple cases, or a default case just to extract the associated value is gaudy.
enum CircularReasoning {
case justPi(pi: Double)
case pizzaPie(howMany: Int)
}
var piInTheSky : Double
let whatLogic = CircularReasoning(pi: 3.1415926)
⬇️ ⬇️
switch whatLogic {
case .justPi(let pi):
piInTheSky = pi!
default:
break
}
You can use
if case .<enum_case>(let value)
as in TylerP's example, orif case let .<enum_case>(value)
:Both work. I'm not sure why the language includes both variants.
If you only care about one enum type, then either
if
syntax makes sense to me. If you are dealing with more than one possible enum value then the switch version seems cleaner.