I have a codable Enum, that can take the form of a string OR a double because the JSON response I get can either be in a string or a double. I need to extract the double from the enum but I can't figure out why.
enum greeksEnum: Codable, Equatable
{
func encode(to encoder: Encoder) throws {
}
case double(Double), string(String)
init(from decoder: Decoder) throws
{
if let double = try? decoder.singleValueContainer().decode(Double.self)
{
self = .double(double)
return
}
if let string = try? decoder.singleValueContainer().decode(String.self)
{
self = .string(string)
return
}
throw greekError.missingValue
}
enum greekError:Error
{
case missingValue
}
}
How would I be able to extract the double value into a double variable?
This is how I compare the strings:
if (volatility[0] == optionsApp.ExpDateMap.greeksEnum.string("NaN"))
{
}
But when I try to type cast the enum to a type Double I get this error.
self.IV = Double(volatility[0])
Initializer 'init(_:)' requires that 'ExpDateMap.greeksEnum' conform to 'BinaryInteger'
Use the
switch
operator to check the case of your enum and extract its associated value:If you only need one case and not all of them, use
if-case-let
orguard-case-let
:Tip: Always name your types in CapitalizedWords (i.e.
GreeksEnum
andGreekError
rather thangreeksEnum
andgreekError
, that is a common standard in Swift).