How to exclude properties from Swift 4's Codable

后端 未结 6 1280
感情败类
感情败类 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:10

    I have used protocol and its extension along with AssociatedObject to set and get image (or any property which needs to be excluded from Codable) property.

    With this we dont have to implement our own Encoder and Decoder

    Here is the code, keeping relevant code for simplicity:

    protocol SCAttachmentModelProtocol{
        var image:UIImage? {get set}
        var anotherProperty:Int {get set}
    }
    extension SCAttachmentModelProtocol where Self: SCAttachmentUploadRequestModel{
        var image:UIImage? {
            set{
                //Use associated object property to set it
            }
            get{
                //Use associated object property to get it
            }
        }
    }
    class SCAttachmentUploadRequestModel : SCAttachmentModelProtocol, Codable{
        var anotherProperty:Int
    }
    

    Now, whenever we want to access the Image property we can use on the object confirming to protocol (SCAttachmentModelProtocol)

提交回复
热议问题