3

最近我加入了一个项目并从符合我想出的这个扩展的类型Codable中获取一个对象,JSONEncodable

extension Encodable {

    /// Converting object to postable JSON
    func toJSON(_ encoder: JSONEncoder = JSONEncoder()) -> [String: Any] {
        guard let data = try? encoder.encode(self),
              let object = try? JSONSerialization.jsonObject(with: data, options: .allowFragments),
              let json = object as? [String: Any] else { return [:] }
        return json
    }
}

这很好用,但有没有更好的方法来达到同样的效果?

4

1 回答 1

10

我的建议是命名函数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
    }
}
于 2018-10-22T07:34:54.283 回答