【问题标题】:Swift Generic does not show nilSwift Generic 不显示 nil
【发布时间】:2019-02-25 19:06:19
【问题描述】:

我有以下一般结构,其中data 可以是任何其他可编码对象

struct GeneralResponse<T:Codable>: Codable {
    let message: String
    let status: Bool
    let data: T?

    enum CodingKeys: String, CodingKey {
        case message = "Message"
        case status = "Status"
        case data = "Data"
    }

}

我有 Follow Like 响应可编码类,将在 GeneralResponse 中用作 data

class ImgLike: Codable {
    let id: Int?
    let imageID, user: String?

    @available(*, deprecated, message: "Do not use.")
    private init() {
        fatalError("Swift 4.1")
    }
    enum CodingKeys: String, CodingKey {
        case id = "ID"
        case imageID = "ImageID"
        case user = "User"
    }

}

问题 1 :当令牌在 API 上过期时,响应 data 仍为空 {} 仍然显示具有所有 nil 属性的 ImgLike 对象。为什么它不显示数据为零?

然后,如果我检查 object?.data == nil 它显示为 false !所以我需要检查每个属性

问题 2:在 ImgLike 如果我使用自定义编码功能。 GeneralResponse not parsed with ImgLike not parsed 它在 catch 语句中显示错误

required init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    imageID =  try values.decode(String.self, forKey: .imageID)
    user = try values.decode(String.self, forKey: .user)

    do {
        id = Int(try values.decode(String.self, forKey: .id))

    } catch {
        id = try values.decode(Int.self, forKey: .id)

    }
}

【问题讨论】:

    标签: swift codable


    【解决方案1】:
    1. Swift-nil 的等效项是 JSON-null 和 JSON-not-set。 {} 是 JSON 格式的有效字典,因此不是 Swift-nil。

    2. 我猜你的意思是在使用自定义解码器功能时会出错?这是意料之中的,因为默认解码器使用 decodeIfPresent 而不是 decode 来解码可选项,因为它们不允许被设置。
      而且由于您解码了一个空字典{},因此没有任何值存在/设置。

    计算 dict 中的键以避免从 JSON-{} 解码

    这个CodingKey-struct 接受它得到的每一个键。

    fileprivate struct AllKeysAllowed: CodingKey {
        var stringValue: String
        var intValue: Int?
        init?(stringValue: String) {
            self.stringValue = stringValue
        }
        init?(intValue: Int) {
            self.intValue = intValue
            stringValue = "\(intValue)"
        }
    }
    
    struct GeneralResponse<T:Codable>: Decodable {
        let message: String
        let status: Bool
        let data: T?
    
        enum CodingKeys: String, CodingKey {
            case message = "Message"
            case status = "Status"
            case data = "Data"
        }
    
        public init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
    
            message = try container.decode(String.self, forKey: .message)
            status = try container.decode(Bool.self, forKey: .status)
    

    将.data 解码为已接受所有密钥的容器。
    然后JSON-dictionary 中的键数可以用dataContainer.allKeys.count 读取。

            let dataContainer = try container.nestedContainer(keyedBy: AllKeysAllowed.self, forKey: .data)
            if dataContainer.allKeys.count != 0 {
                data = try container.decode(T.self, forKey: .data)
            } else {
                data = nil
            }
        }
    }
    

    【讨论】:

    • 在 Swift 中 nil 的等价物是 null 并且在 JSON 中没有设置。 {} 是 JSON 中的有效字典,因此不是 nil。 是的,您是对的 {} 不是 nil 它是空的。但是我已经解码了应该为空 {} 的 ImgLike。即使 T 通常响应是可选的
    • 但是我已经解码了 ImgLike,它应该是空的 {}。:data 的唯一情况当“data“: {}在JSON中不存在时,可以为nil。您可以将ImgLike 的属性设为非可选,然后解码ImgLike 会引发错误,您可以使用GeneralResponse 中的required init(from:) 处理该错误,方法是通过捕获并忽略它的错误来忽略解析错误。跨度>
    • 刮掉 do-catch 部分。我添加了一个解决方案。
    • 谢谢,我会尽快尝试
    【解决方案2】:

    请注意,默认的Codable 实现使用decodeIfPresent 而不是decode。即使 JSON 中不存在密钥,decodeIfPresent 也不会抛出错误。它只会返回nil。所以一个空的 JSON 字典没有 KVP,所以所有的属性都设置为nil。

    在Codable 的自定义实现中,您使用的是decode,如果找不到密钥,将抛出错误。

    之所以object?.data != nil 是因为object?.data 是一个ImgLike???。您将可选项包装在可选项中的可选项中。我看到object 的类型是GeneralResponse&lt;ImgLike?&gt;?。这将使data 的类型为ImgLike??。我不认为这是你的意图。您可能打算使用GeneralRepsonse&lt;ImgLike&gt;。您可能忘记在某处打开可选的包装。你还需要解开最外面的可选:

    if let nonNilObject = object {
       // nonNilObject.data is of type ImgLike?
    }
    

    【讨论】:

      【解决方案3】:

      如前所述,解码器不会将空字典视为nil。

      您可以通过一个小协议和KeyedDecodingContainer 的扩展以通用方式添加此功能

      public protocol EmptyDictionaryRepresentable {
          associatedtype CodingKeys : RawRepresentable where CodingKeys.RawValue == String
          associatedtype CodingKeyType: CodingKey = Self.CodingKeys
      }
      
      extension KeyedDecodingContainer {
          public func decodeIfPresent<T>(_ type: T.Type, forKey key: KeyedDecodingContainer.Key) throws -> T?
              where T : Decodable & EmptyDictionaryRepresentable
          {
              guard contains(key) else { return nil }
              let container = try nestedContainer(keyedBy: type.CodingKeyType.self, forKey: key)
              return container.allKeys.isEmpty ? nil : try decode(T.self, forKey: key)
          }
      }
      

      只需将EmptyDictionaryRepresentable 一致性添加到ImgLike,即可推断出关联的类型。

      class ImgLike: Codable, EmptyDictionaryRepresentable {
      

      ImgLike 中的属性甚至可以声明为非可选

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-07
        • 2016-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多