swift - 检索具有多个案例的类字符串
问题描述
我想从此枚举中检索数据以在实例中使用。我不确定如何从我的 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)
}
}
}
解决方案
鉴于这stringValue
是Value
您可以切换的类型。
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]]`
}
推荐阅读
- javascript - 成功从过滤器获取结果后如何在 Laravel 8 的刀片文件中显示
- html - 是否允许 p 标签中的按钮标签?
- javascript - 实现 toJSON() 方法是否足以使任何类实例可序列化?
- google-apps-script - 考勤管理
- powershell - 如何只允许在 Read-Host 中输入 Y/N 而不必在 Powershell 中按 Enter?
- reactjs - 映射列表 React.js 后更改 className
- javascript - JSON.parse 反序列化字符串时是否调用回调?
- zsh - 使用 /bin/zsh -c print 时如何显示输出?
- javascript - 如何控制台记录字符串中的单词?
- sql - SQL Server - 可以回滚 DDL 命令吗?