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

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

问题描述

tl; dr

是否可以实例化关联类型为无效?

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

背景

I' m使用简单的 Result 枚举(类似于反身结果):

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

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

现在,我想用这个枚举来表示一个不会产生实际结果值的操作的结果;操作成功失败。为此,我将类型定义为 Result< Void> ,但是我在如何创建Result实例方面苦苦挣扎,都没有 let res:结果<无效> = .success let res:结果< Void> = .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中,您可以省略类型的关联值无效

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

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

在Swift 4中,您必须传递类型为<$ c $的关联值c>无效:

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天全站免登陆