作为对查询的响应,我得到的答案是"error“:None,我无法处理将其分配给给定类型的问题。也许有人有一个解决方案或想法如何绕过这个值。
我的代码:
import Foundation
struct Test: Codable {
let id: Int
let error: ???????
}
let json = """
{"error": None,
"id": 1
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let product = try decoder.decode(Test.self, from: json)
print(product.id)发布于 2018-02-14 07:23:42
首先,该结构没有正确地符合->所需的协议,如下所示。
其次,为了抛出来自解码器的错误,你应该尝试这样做;
do {
try decoder.decode()
// handle data here
} catch {
// handle error
}第三,你的错误常量可以是很多东西。Error()、NSError()、自定义对象...如果您的error类型为Error(),并且值为nothing,则需要执行一条if let语句来捕获nil值,并且不允许该值为"None“。例如:
var theError = nil
if let error = myError {
// because you hard coded the value of error to be "None" return nil instead
// else return the actual value of the error
if error == "None" { return theError } else {
theError = error
print("error has a value! ", error.localizedDescription)
}
} else {
print("There is no error")
}
return theError // returns nil instead of "None" or it returns a real error

https://stackoverflow.com/questions/48777120
复制相似问题