具有 Void 关联类型的通用 Swift 4 枚举 [英] Generic Swift 4 enum with Void associated type

查看:27
本文介绍了具有 Void 关联类型的通用 Swift 4 枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

tl;dr

是否可以实例化具有 Void 类型的关联值的通用 Swift 4 枚举成员?

Is it possible to instantiate a generic Swift 4 enum member with an associated value of type Void?

背景

我使用的是一个简单的Result枚举(类似于反典型结果):

I'm using a simple Result enum (similar to antitypical Result):

enum Result<T> {
  case success(T)
  case error(Error?)
}

现在我想用这个枚举来表示一个不产生实际结果值的操作的结果;操作要么成功,要么失败.为此,我将类型定义为 Result,但我在如何创建 Result 实例方面苦苦挣扎,let res: Result= .successlet res: Result= .success() 有效.

Now I'd like to use this enum to represent the result of an operation which does not yield an actual result value; the operation is either succeeded or failed. For this I'd define the type as Result<Void>, but I'm struggling with how to create the Result instance, neither let res: Result<Void> = .success nor let res: Result<Void> = .success() works.

推荐答案

在 Swift 3 中你可以省略 Void 类型的关联值:

In Swift 3 you can omit the associated value of type Void:

let res: Result<Void> = .success()

在 Swift 4 中,你必须传递一个 Void 类型的关联值:

In Swift 4 you have to pass an associated value of type Void:

let res: Result<Void> = .success(())
// Or just:
let res = Result.success(())

这篇关于具有 Void 关联类型的通用 Swift 4 枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆