如果您不介意数据移位,可以使用以下方法:
extension Encodable { func asDictionary() throws -> [String: Any] { let data = try JSonEnprer().enpre(self) guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else { throw NSError() } return dictionary }}
或可选变体
extension Encodable { var dictionary: [String: Any]? { guard let data = try? JSonEnprer().enpre(self) else { return nil } return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap {Fooas? [String: Any] } }}
假设
Codable符合
Encodable或确实
let struct = Foo(a: 1, b: 2)let dict = try struct.asDictionary()let optionalDict = struct.dictionary可以做到这一点。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)