本文介绍了在swift4中使类符合可编码协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使结构符合Codable(可编码和可解码)协议非常容易:只需声明它即可.但是,如果我想使类符合Codable,是否必须编写所有锅炉代码(CodingEnum,init(来自解码器:Decoder),encode(至编码器:Encoder)等)?

Make conforming struct to Codable (Encodable & Decodable) protocol is super easy: just declare it. But do I have to write all boiler code (CodingEnum, init(from decoder: Decoder), encode(to encoder: Encoder), etc) if I want make class conforming to Codable?

推荐答案

不,您不需要这样做.示例:

No, you haven't to do it. Example:

import Foundation

class Message: Codable {
    let id: Int = 1
    let text: String = "Hello"
}

let message = Message()
let encoder = JSONEncoder()
let json = try encoder.encode(message)
print(String(data: json, encoding: String.Encoding.utf8)!)

这篇关于在swift4中使类符合可编码协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:01