我想在swift
中获得一系列对象的jsonclass action {
var ts: Int;
var winner: Int;
var meta: [Int: String];
init(ts : Int, winner: Int, meta: [Int: String]) {
self.ts = ts;
self.winner = winner;
self.meta = meta;
}
}
var actions:[action] = []
let thisAction = action(ts: 123, winner: 1, meta: [:]);
actions.append(thisAction);
let jsonEncoder = JSONEncoder();
let jsonData = try jsonEncoder.encode(actions);
但是我有以下错误:
致命错误:阵列< action>不符合编码,因为动作不符合编码。swift/stdlib/public/core/codable.swift,第3962行
错误消息非常清楚,您需要在Action
类中继承Codable
。
class Action: Codable {
var ts: Int
var winner: Int
var meta: [Int: String]
init(ts : Int, winner: Int, meta: [Int: String]) {
self.ts = ts
self.winner = winner
self.meta = meta
}
}
提示1:在您的Action
类上使用CA
提示2:不使用 ;
,在swift
提示3:使用Do-Try-Catch:
do {
let jsonData = try JSONEncoder().encode(actions)
print(jsonData)
} catch let error {
print(error)
}