Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
使结构符合 Codable (Encodable & Decodable) 协议非常容易:只需声明它。但是,如果我想让类符合 Codable,我是否必须编写所有锅炉代码(CodingEnum、init(来自解码器:解码器)、编码(到编码器:编码器)等)?
不,你不必这样做。例子:
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)!)