4的可解码内容来解码虚空

4的可解码内容来解码虚空

本文介绍了借助Swift 4的可解码内容来解码虚空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用的REST请求:

I have a generic REST request:

struct Request<T> {…}

T是请求的返回类型,例如:

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

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

现在,我想表示泛型类型必须符合Decodable的要求,以便我可以解码来自服务器的JSON响应:

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 {…}

这很有意义并且可以工作–直到我收到一个没有响应的请求,即Request<Void>.编译器对此不满意:

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'

我通过将Decodable一致性添加到Void来解决这个问题的顽强尝试很快被编译器发现:

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

让请求在返回类型上通用是正确的.有没有办法使它与Void返回类型一起使用? (例如,仅在服务器上创建内容但不返回任何内容的请求.)

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.)

推荐答案

一个简单的解决方法是引入一个自定义的"no-reply"类型,该类型将替换Void:

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

struct NoReply: Decodable {}

无法将Void符合Decodable. Void只是空元组()的类型别名,并且元组此刻无法遵循协议,但最终会遵循.

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.

这篇关于借助Swift 4的可解码内容来解码虚空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:18