相关疑难解决方法(0)

使用Decodable进行JSON解析时,optional和decodeIfPresent有什么区别?

Codable第一次使用Swift 4的协议,我无法理解使用decodeIfPresentfrom Decodable.

/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated …
Run Code Online (Sandbox Code Playgroud)

swift swift4 codable decodable

23
推荐指数
3
解决办法
7532
查看次数

JSON字符串中出现意外的nil

我在我的应用程序中解析JSON,并且一些JSON具有nil我处理的值.但是,该应用程序仍然显示JSON包含nil值的错误.我的代码:

struct Response : Decodable {
let articles: [Article]
 }

struct Article: Decodable {

let title: String
let description : String
let url : String
let urlToImage : String
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
     guard let data = data else { return }
     do {
     let article =  try JSONDecoder().decode(Response.self , from : data)
     for i in 0...article.articles.count - 1 {
         if type(of: article.articles[i].title) == NSNull.self {
             beforeLoadNewsViewController.titleArray.append("")
         } else {
             beforeLoadNewsViewController.titleArray.append(article.articles[i].title)
         } …
Run Code Online (Sandbox Code Playgroud)

null json swift

1
推荐指数
1
解决办法
3096
查看次数

标签 统计

swift ×2

codable ×1

decodable ×1

json ×1

null ×1

swift4 ×1