socketio / socket.io-client-swift

Other
5.22k stars 841 forks source link

Decode responses to Struct via Codable #952

Open kristoff-it opened 6 years ago

kristoff-it commented 6 years ago

At the moment objects coming in via the socket get decoded as [String: Any], and to obtain a struct from a response one has to manually implement something along the lines of init(dict: dataComingFromSocketIO) in which every single property has to be manually mapped.

Some answers on Stack overflow even suggest to serialize the Dictionary back to json and use another library to parse it back into a Struct using the Codable protocol, which is... not optimal.

Considering that communications through the socket come encoded as json, it seems plausible to inject the same behavior during the initial decoding step using the standard json decoder.

The interface could look something like this: func emit<U: Codable> (_ event: String, decodeAs: U, _ items: SocketData...)

Is there a reason why this might be harder than what it seems? Or maybe is someone already working on that?

If it's not too involved I might try to start working on a PR, let me know please. Thanks!

kristoff-it commented 6 years ago

Actually, data currently gets decoded as [Any], small inprecision on my part.

nuclearace commented 6 years ago

It gets a bit more complicated since socket.io supports sending raw binary in objects at the application level. Internally it has to go through each object and remove the binary and add placeholders for them. So you would still have to handle this case.

kristoff-it commented 6 years ago

I see, I definitely don't know enough about how contents are framed to work on this. Maybe this feature should be kept in mind for when the project will undergo a big rewrite, as it seems to me that a cast to a struct is a fairly idiomatic use case for Swift.

nuclearace commented 6 years ago

Right, this is why I introduced SocketData

eddieSullivan commented 5 years ago

@nuclearace just a note that Swifts JSONEncoder has a provision for binary data via its dataEncodingStrategy field.