How to handle partially dynamic JSON with Swift Codable? : <p>I've got some JSON messages coming in over a websocket connection.</p>

<pre><code>// sample message
{
  type: "person",
  data: {
    name: "john"
  }
}

// some other message
{
  type: "location",
  data: {
    x: 101,
    y: 56
  }
}
</code></pre>

<p>How can I convert those messages into proper structs using Swift 4 and the Codable protocol?</p>

<p>In Go I can do something like: "Hey at the moment I only care about the <code>type</code> field and I'm not interested in the rest (the <code>data</code> part)." It would look like this</p>

<pre><code>type Message struct {
  Type string `json:"type"`
  Data json.RawMessage `json:"data"`
}
</code></pre>

<p>As you can see <code>Data</code> is of type <code>json.RawMessage</code> which can be parsed later on. Here is a full example <a href="https://golang.org/pkg/encoding/json/#example_RawMessage_unmarshal" rel="noreferrer">https://golang.org/pkg/encoding/json/#example_RawMessage_unmarshal</a>.</p>

<p>Can I do something similar in Swift? Like (haven't tried it yet)</p>

<pre><code>struct Message: Codable {
  var type: String
  var data: [String: Any]
}
</code></pre>

<p>Then <code>switch</code> on the <code>type</code> to convert the dictionary into proper structs. Would that work?</p>
