我的建议是命名函数
toDictionary
并将可能的错误移交给调用者。条件向下强制转换失败(类型不匹配)被包装在
typeMismatch
判定元件
编码错误。
extension Encodable {
/// Converting object to postable dictionary
func toDictionary(_ encoder: JSONEncoder = JSONEncoder()) throws -> [String: Any] {
let data = try encoder.encode(self)
let object = try JSONSerialization.jsonObject(with: data)
guard let json = object as? [String: Any] else {
let context = DecodingError.Context(codingPath: [], debugDescription: "Deserialized object is not a dictionary")
throw DecodingError.typeMismatch(type(of: object), context)
}
return json
}
}