首页 > 解决方案 > 忽略 swift Codable 中的以下属性?

问题描述

我有这个 Account 结构。当我发送“POST”端点并使用它们将成功解码返回给 swift 对象时,我想忽略以下属性环境和编码到 JSON 对象的 Id

更新我有这个错误属性类型'[Environment]'与它的包装器类型'SkipEncode'的'wrappedValue'属性不匹配

struct Account: Codable {
    let accountID, displayName, managedByID, id: String
    let environments: [Environment]
    let contacts: [Contact]

    enum CodingKeys: String, CodingKey {
        case accountID
        case displayName
        case managedID
        case id
        case environments
        case contacts
    }
}

标签: jsonswiftcodableurlsession

解决方案


另一种方法,如果您不想手动实现encode(to:)并放弃Codable自动合成的好处,您可以创建一个属性包装器作为标记要跳过的属性的一种方式:

@propertyWrapper
struct SkipEncode<T> {
   var wrappedValue: T
}

extension SkipEncode: Decodable where T: Decodable {
   init(from decoder: Decoder) throws {
      let container = try decoder.singleValueContainer()
      self.wrappedValue = try container.decode(T.self)
   }
}

extension SkipEncode: Encodable {
   func encode(to encoder: Encoder) throws {
      // nothing to do here
   }
}

extension KeyedEncodingContainer {
   mutating func encode<T>(_ value: SkipEncode<T>, forKey key: K) throws {
      // overload, but do nothing
   }
}

然后你可以@SkipEncode像这样使用:

struct Account: Codable {
    let accountID, displayName, managedByID: String
    let contacts: [Contact]
    
    @SkipEncode
    let id: String

    @SkipEncode 
    let environments: [Environment]
}

推荐阅读