gpt4 book ai didi

Swift Codable 如何使用 Any 类型?

转载 作者:搜寻专家 更新时间:2023-11-01 05:31:45 24 4
gpt4 key购买 nike

当我尝试访问“value”的值(例如在 label.text 中使用它)时,出现错误

Cannot assign value of type 'MyValue?' to type 'String?'

当我将值打印到终端时,它说...

unknown context at 0x109d06188).MyValue.string...

如何解决这个问题?

struct Root: Codable {
let description,id: String
let group,groupDescription: String?
let name: String
let value: MyValue

enum CodingKeys: String, CodingKey {
case description = "Description"
case group = "Group"
case groupDescription = "GroupDescription"
case id = "Id"
case name = "Name"
case value = "Value"
}
}

enum MyValue: Codable {
case string(String)
case innerItem(InnerItem)

init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(String.self) {
self = .string(x)
return
}
if let x = try? container.decode(InnerItem.self) {
self = .innerItem(x)
return
}
throw DecodingError.typeMismatch(MyValue.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for MyValue"))
}

func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .string(let x):
try container.encode(x)
case .innerItem(let x):
try container.encode(x)
}
}
}

最佳答案

您可以通过遵守 rawRepresentable 协议(protocol)来获取标签的字符串值:

enum MyValue: Codable, RawRepresentable {


var rawValue: String {
switch self {
case .string(let stringVal):
return stringVal
case .innerItem(let myVal):
return String(describing: myVal)
}
}

typealias RawValue = String

init?(rawValue: String) {
return nil
}



case string(String)
case innerItem(InnerItem)

}

let myVal = MyValue.string("testString")
var strVal: String = myVal.rawValue // testString

关于Swift Codable 如何使用 Any 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57888659/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com