簡體   English   中英

如何在 Swift 中將枚舉類型轉換為 Double

[英]How to type cast an Enum to a Double in Swift

我有一個可編碼的枚舉,它可以采用字符串或雙精度的形式,因為我得到的 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])

初始化程序 '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)")
}

提示:始終以 CapitalizedWords 命名您的類型(即, GreeksEnumGreekError而不是greeksEnumgreekError ,這是 Swift 中的通用標准)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM