我有一个结构,其中一些值会得到整数或字符串,所以我在我的结构中使用这个结构以正确的方式解析 JSON 但问题是当我想打印值时它会打印字符串(“1") 而不是 1。
public struct player1_result_sheet : Decodable {
let ans_1 : QuantumValue?
let ans_2 : QuantumValue?
let ans_3 : QuantumValue?
let ans_4 : QuantumValue?
}
enum QuantumValue: Decodable {
case int(Int), string(String)
init(from decoder: Decoder) throws {
if let int = try? decoder.singleValueContainer().decode(Int.self) {
self = .int(int)
return
}
if let string = try? decoder.singleValueContainer().decode(String.self) {
self = .string(string)
return
}
throw QuantumError.missingValue
}
enum QuantumError:Error {
case missingValue
}
}
这里是解码后的打印:
(self.res?.response?.detailData?[indexPath.row].player1_result_sheet?.ans_1!)!
最佳答案
如果你想在没有枚举包装器的情况下打印值,只需实现description
:
extension QuantumValue: CustomStringConvertible {
public var description: String {
switch self {
case let .string(string):
return string
case let .int(number):
return "\(number)"
}
}
}
关于swift - 在 Swift 4 中解码结构中的字符串或 int 值将返回字符串 ("1"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53894747/