[英]JSON Codable Swift 4 “None” type
In response to the query, the answer "error" comes to me: None, I can not cope with assigning it to a given type. 响应该查询,答案“错误”出现在我的身上:无,我无法应付将其分配给给定类型的问题。 Maybe someone has a solution or an idea how to bypass this value.
也许有人有解决方案或想法如何绕过此值。
My code: 我的代码:
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)
First, The struct doesn't properly conform to the protocols required -> See Below. 首先,该结构未正确符合所需的协议->参见下文。
Second to throw the error from the decoder you should try to do this; 其次,从解码器抛出错误,您应该尝试执行此操作。
do {
try decoder.decode()
// handle data here
} catch {
// handle error
}
Third, your error constant could be many things. 第三,错误常数可能有很多。
Error()
, NSError()
, a custom object... If you make the error
of type Error()
and the value is nothing, you'll want to do an if let
statement to catch a nil value and not allow the value be "None". Error()
NSError()
自定义对象...如果你做error
类型的Error()
和价值是什么,你想要做的if let
语句来捕获一个零值,而不是允许值成为“无”。 For example: 例如:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.