How to exclude properties from Swift 4's Codable

后端 未结 6 1278
感情败类
感情败类 2020-12-23 15:40

Swift 4\'s new Encodable/Decodable protocols make JSON (de)serialization quite pleasant. However, I have not yet found a way to have fine-grained c

6条回答
  •  误落风尘
    2020-12-23 16:24

    You can use computed properties:

    struct Person: Codable {
      var firstName: String
      var lastName: String
      var nickname: String?
    
      var nick: String {
        get {
          nickname ?? ""
        }
      }
    
      private enum CodingKeys: String, CodingKey {
        case firstName, lastName
      }
    }
    

提交回复
热议问题