回答:
データのシフトを少し気にしない場合は、次のようなものを使用できます。
extension Encodable {
  func asDictionary() throws -> [String: Any] {
    let data = try JSONEncoder().encode(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? JSONEncoder().encode(self) else { return nil }
    return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
  }
}にFoo準拠している、Codableまたは実際に準拠していると仮定すると、Encodableこれを実行できます。
let struct = Foo(a: 1, b: 2)
let dict = try struct.asDictionary()
let optionalDict = struct.dictionary他の方法に移動したい場合は(init(any))、このInitオブジェクトを調べてください。辞書/配列を使用してCodableに準拠しています
ここでの簡単な実装であるDictionaryEncoder/ DictionaryDecoderそのラップはJSONEncoder、JSONDecoderとJSONSerializationも戦略をデコード/エンコード処理していること、...
class DictionaryEncoder {
    private let encoder = JSONEncoder()
    var dateEncodingStrategy: JSONEncoder.DateEncodingStrategy {
        set { encoder.dateEncodingStrategy = newValue }
        get { return encoder.dateEncodingStrategy }
    }
    var dataEncodingStrategy: JSONEncoder.DataEncodingStrategy {
        set { encoder.dataEncodingStrategy = newValue }
        get { return encoder.dataEncodingStrategy }
    }
    var nonConformingFloatEncodingStrategy: JSONEncoder.NonConformingFloatEncodingStrategy {
        set { encoder.nonConformingFloatEncodingStrategy = newValue }
        get { return encoder.nonConformingFloatEncodingStrategy }
    }
    var keyEncodingStrategy: JSONEncoder.KeyEncodingStrategy {
        set { encoder.keyEncodingStrategy = newValue }
        get { return encoder.keyEncodingStrategy }
    }
    func encode<T>(_ value: T) throws -> [String: Any] where T : Encodable {
        let data = try encoder.encode(value)
        return try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]
    }
}
class DictionaryDecoder {
    private let decoder = JSONDecoder()
    var dateDecodingStrategy: JSONDecoder.DateDecodingStrategy {
        set { decoder.dateDecodingStrategy = newValue }
        get { return decoder.dateDecodingStrategy }
    }
    var dataDecodingStrategy: JSONDecoder.DataDecodingStrategy {
        set { decoder.dataDecodingStrategy = newValue }
        get { return decoder.dataDecodingStrategy }
    }
    var nonConformingFloatDecodingStrategy: JSONDecoder.NonConformingFloatDecodingStrategy {
        set { decoder.nonConformingFloatDecodingStrategy = newValue }
        get { return decoder.nonConformingFloatDecodingStrategy }
    }
    var keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy {
        set { decoder.keyDecodingStrategy = newValue }
        get { return decoder.keyDecodingStrategy }
    }
    func decode<T>(_ type: T.Type, from dictionary: [String: Any]) throws -> T where T : Decodable {
        let data = try JSONSerialization.data(withJSONObject: dictionary, options: [])
        return try decoder.decode(type, from: data)
    }
}使い方はJSONEncoder/に似ていJSONDecoderます…
let dictionary = try DictionaryEncoder().encode(object)そして
let object = try DictionaryDecoder().decode(Object.self, from: dictionary)便宜上、これをすべてリポジトリに入れました… https://github.com/ashleymills/SwiftDictionaryCoding
CodableFirebaseというライブラリを作成しました。その最初の目的は、Firebase Databaseで使用することでしたが、実際に必要なことを実行します。これは、辞書やその他のタイプを作成するのと同じJSONDecoderですが、ここで二重変換を行う必要はありません。あなたが他の答えでするように。したがって、次のようになります。
import CodableFirebase
let model = Foo(a: 1, b: 2)
let dict = try! FirebaseEncoder().encode(model)それが最善の方法かどうかはわかりませんが、次のようなことは間違いなくできます。
struct Foo: Codable {
    var a: Int
    var b: Int
    init(a: Int, b: Int) {
        self.a = a
        self.b = b
    }
}
let foo = Foo(a: 1, b: 2)
let dict = try JSONDecoder().decode([String: Int].self, from: JSONEncoder().encode(foo))
print(dict)それを行うための組み込みの方法はありません。上記の答えあなたは何のパフォーマンスの問題を持っていないならば、あなたは受け入れることができますJSONEncoder+のJSONSerialization実装を。
しかし、私は標準ライブラリの方法でエンコーダ/デコーダオブジェクトを提供したいと思います。
class DictionaryEncoder {
    private let jsonEncoder = JSONEncoder()
    /// Encodes given Encodable value into an array or dictionary
    func encode<T>(_ value: T) throws -> Any where T: Encodable {
        let jsonData = try jsonEncoder.encode(value)
        return try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)
    }
}
class DictionaryDecoder {
    private let jsonDecoder = JSONDecoder()
    /// Decodes given Decodable type from given array or dictionary
    func decode<T>(_ type: T.Type, from json: Any) throws -> T where T: Decodable {
        let jsonData = try JSONSerialization.data(withJSONObject: json, options: [])
        return try jsonDecoder.decode(type, from: jsonData)
    }
}あなたは次のコードでそれを試すことができます:
struct Computer: Codable {
    var owner: String?
    var cpuCores: Int
    var ram: Double
}
let computer = Computer(owner: "5keeve", cpuCores: 8, ram: 4)
let dictionary = try! DictionaryEncoder().encode(computer)
let decodedComputer = try! DictionaryDecoder().decode(Computer.self, from: dictionary)ここでは、例を短くするために強制的に試行しています。本番コードでは、エラーを適切に処理する必要があります。
一部のプロジェクトでは、迅速なリフレクションを使用しています。ただし、ネストされたコード化可能なオブジェクトは、そこにもマップされないことに注意してください。
let dict = Dictionary(uniqueKeysWithValues: Mirror(reflecting: foo).children.map{ ($0.label!, $0.value) })CodableJSON / Plists /その他にアクセスするつもりがなくても、辞書との間のエンコードに使用できるだけの価値はあると思います。ディクショナリを返す、またはディクショナリを期待する多くのAPIがあり、無限のボイラープレートコードを記述することなく、それらをSwift構造体またはオブジェクトと簡単に交換できることは素晴らしいことです。
Foundation JSONEncoder.swiftソースに基づいたコードを試してみました(実際には辞書のエンコード/デコードを内部で実装していますが、エクスポートしていません)。
コードはここにあります:https : //github.com/elegantchaos/DictionaryCoding
まだ大雑把ですが、たとえば、デコード時に欠損値をデフォルトで埋めることができるように、少し拡張しました。
私は、変更したPropertyListEncoderを単にバイナリ形式辞書から最終的なシリアライゼーションを除去することによって、DictionaryEncoderにスイフトプロジェクトから。同じことを自分で行うことも、私のコードをここから取得することもできます
次のように使用できます。
do {
    let employeeDictionary: [String: Any] = try DictionaryEncoder().encode(employee)
} catch let error {
    // handle error
}これを処理するための簡単な要点を書きました(Codableプロトコルを使用していません)。注意してください。値の型チェックは行われず、エンコード可能な値に対して再帰的に機能しません。
class DictionaryEncoder {
    var result: [String: Any]
    init() {
        result = [:]
    }
    func encode(_ encodable: DictionaryEncodable) -> [String: Any] {
        encodable.encode(self)
        return result
    }
    func encode<T, K>(_ value: T, key: K) where K: RawRepresentable, K.RawValue == String {
        result[key.rawValue] = value
    }
}
protocol DictionaryEncodable {
    func encode(_ encoder: DictionaryEncoder)
}Codableでこれを行う簡単な方法はありません。構造体にEncodable / Decodableプロトコルを実装する必要があります。あなたの例では、以下のように書く必要があるかもしれません
typealias EventDict = [String:Int]
struct Favorite {
    var all:EventDict
    init(all: EventDict = [:]) {
        self.all = all
    }
}
extension Favorite: Encodable {
    struct FavoriteKey: CodingKey {
        var stringValue: String
        init?(stringValue: String) {
            self.stringValue = stringValue
        }
        var intValue: Int? { return nil }
        init?(intValue: Int) { return nil }
    }
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: FavoriteKey.self)
        for eventId in all {
            let nameKey = FavoriteKey(stringValue: eventId.key)!
            try container.encode(eventId.value, forKey: nameKey)
        }
    }
}
extension Favorite: Decodable {
    public init(from decoder: Decoder) throws {
        var events = EventDict()
        let container = try decoder.container(keyedBy: FavoriteKey.self)
        for key in container.allKeys {
            let fav = try container.decode(Int.self, forKey: key)
            events[key.stringValue] = fav
        }
        self.init(all: events)
    }
}私はここにポッドを作りましたhttps://github.com/levantAJ/AnyCodable デコードとエンコード を容易にし[String: Any]、[Any]
pod 'DynamicCodable', '1.0'そして、あなたはデコードしてエンコードすることができ[String: Any]、[Any]
import DynamicCodable
struct YourObject: Codable {
    var dict: [String: Any]
    var array: [Any]
    var optionalDict: [String: Any]?
    var optionalArray: [Any]?
    enum CodingKeys: String, CodingKey {
        case dict
        case array
        case optionalDict
        case optionalArray
    }
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        dict = try values.decode([String: Any].self, forKey: .dict)
        array = try values.decode([Any].self, forKey: .array)
        optionalDict = try values.decodeIfPresent([String: Any].self, forKey: .optionalDict)
        optionalArray = try values.decodeIfPresent([Any].self, forKey: .optionalArray)
    }
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(dict, forKey: .dict)
        try container.encode(array, forKey: .array)
        try container.encodeIfPresent(optionalDict, forKey: .optionalDict)
        try container.encodeIfPresent(optionalArray, forKey: .optionalArray)
    }
}SwiftyJSONを使用している場合は、次のようにすることができます。
JSON(data: JSONEncoder().encode(foo)).dictionaryObject
注:この辞書
parametersをAlamofireリクエストに渡すこともできます。
これはプロトコルベースのソリューションです:
protocol DictionaryEncodable {
    func encode() throws -> Any
}
extension DictionaryEncodable where Self: Encodable {
    func encode() throws -> Any {
        let jsonData = try JSONEncoder().encode(self)
        return try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)
    }
}
protocol DictionaryDecodable {
    static func decode(_ dictionary: Any) throws -> Self
}
extension DictionaryDecodable where Self: Decodable {
    static func decode(_ dictionary: Any) throws -> Self {
        let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: [])
        return try JSONDecoder().decode(Self.self, from: jsonData)
    }
}
typealias DictionaryCodable = DictionaryEncodable & DictionaryDecodableそしてここにそれを使用する方法があります:
class AClass: Codable, DictionaryCodable {
    var name: String
    var age: Int
    
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}
struct AStruct: Codable, DictionaryEncodable, DictionaryDecodable {
    
    var name: String
    var age: Int
}
let aClass = AClass(name: "Max", age: 24)
if let dict = try? aClass.encode(), let theClass = try? AClass.decode(dict) {
    print("Encoded dictionary: \n\(dict)\n\ndata from decoded dictionary: \"name: \(theClass.name), age: \(theClass.age)\"")
}
let aStruct = AStruct(name: "George", age: 30)
if let dict = try? aStruct.encode(), let theStruct = try? AStruct.decode(dict) {
    print("Encoded dictionary: \n\(dict)\n\ndata from decoded dictionary: \"name: \(theStruct.name), age: \(theStruct.age)\"")
}考えてみてください。Encodableインスタンスは、配列などの辞書にシリアライズできないものである可能性があるため、一般的なケースでは質問には答えがありません。
let payload = [1, 2, 3]
let encoded = try JSONEncoder().encode(payload) // "[1,2,3]"それ以外に、私はフレームワークとして同様のものを書きました。