首页 > 解决方案 > 检索具有多个案例的类字符串

问题描述

我想从此枚举中检索数据以在实例中使用。我不确定如何从我的 api 调用中正确检索数据,欢迎提出任何建议。

我的代码

let stringValue = WcProduct[count].metaData![i].value
// {
//     case String // do something
//     case [String: [String: String]] // do something
// }
if stringValue is [String : [String:String]] // maybe?
{
    if (stringValue("1") != "")
    {
                            
    }
}

我的枚举

enum Value: Codable {
    case string(String)
    case stringMapMap([String: [String: String]])
    
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if let x = try? container.decode([String: [String: String]].self) {
            self = .stringMapMap(x)
            return
        }
        if let x = try? container.decode(String.self) {
            self = .string(x)
            return
        }
        throw DecodingError.typeMismatch(Value.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for Value"))
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .string(let x):
            try container.encode(x)
        case .stringMapMap(let x):
            try container.encode(x)
        }
    }
}

错误尝试 1

在此处输入图像描述

标签: swiftenumscaseinstance

解决方案


鉴于这stringValueValue您可以切换的类型。

switch stringValue {
case let .string(singleValue):
    /// use `singleValue`, it has a type of `String`
case let .stringMapMap(mapOfMaps):
    /// use `mapOfMpas`, it has a type of `[String: [String: String]]`  
}

推荐阅读