如何在 Swift 中将 Enum 类型转换为 Double

问题描述

我有一个可编码的枚举,它可以采用字符串或双精度的形式,因为我得到的 JSON 响应可以是字符串或双精度。我需要从枚举中提取双精度值,但我不知道为什么。

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
    }
}

如何将双精度值提取到双精度变量中?

这是我比较字符串的方式:

 if (volatility[0] == optionsApp.ExpDateMap.greeksEnum.string("NaN"))
 {
 }

但是当我尝试将枚举类型转换为 Double 类型时,我收到此错误

self.IV = Double(volatility[0])

Initializer 'init(_:)' 要求 'ExpDateMap.greeksEnum' 符合 'BinaryInteger'

解决方法

使用 switch 运算符检查枚举的大小写并提取其关联值:

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-case-letguard-case-let

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

提示:始终以大写字词命名您的类型(即 GreeksEnumGreekError,而不是 greeksEnumgreekError,这是 Swift 中的通用标准)。