Decoding Void with Swift 4’s Decodable

怎甘沉沦 提交于 2019-12-06 17:45:36

问题


I have a generic REST request:

struct Request<T> {…}

The T is the return type of the request, for example:

struct Animal {…}
let animalRequest = Request<Animal>
let animal: Animal = sendRequest(animalRequest)

Now I would like to express that the generic type has to conform to Decodable so that I can decode the JSON response from the server:

struct Request<T> where T: Decodable {…}
struct Animal: Decodable {…}

This makes sense and works – until I arrive at a request that has no response, a Request<Void>. The compiler is not happy about that one:

Type 'Void' does not conform to protocol 'Decodable'

My mischevious attempt to solve this by adding the Decodable conformance to Void was quickly found out by the compiler:

extension Void: Decodable {…} // Error: Non-nominal type 'Void' cannot be extended

It feels right to have the request generic over the return type. Is there a way to make it work with Void return types? (For example the requests that just create something on the server and don’t return anything.)


回答1:


A simple workaround is to introduce a custom “no-reply” type that would replace Void:

struct NoReply: Decodable {}

Conforming Void to Decodable is not possible. Void is just a type alias for an empty tuple, (), and tuples cannot conform to protocols at this moment, but they will, eventually.



来源:https://stackoverflow.com/questions/45635018/decoding-void-with-swift-4-s-decodable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!