How to type cast an Enum to a Double in Swift

547 views Asked by At

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'

1

There are 1 answers

1
Vadim Belyaev On BEST ANSWER

Use the switch operator to check the case of your enum and extract its associated value:

let x: GreeksEnum = .double(3.14)

switch x {
case .double(let doubleValue):
    print("x is a double: \(doubleValue)")
case .string(let stringValue):
    print("x is a string: \(stringValue)")
}

If you only need one case and not all of them, use if-case-let or guard-case-let:

if case .double(let doubleValue) = x {
    print("x is a double: \(doubleValue)")
}

Tip: Always name your types in CapitalizedWords (i.e. GreeksEnum and GreekError rather than greeksEnum and greekError, that is a common standard in Swift).