具有 Void 关联类型的通用 Swift 4 枚举 [英] Generic Swift 4 enum with Void associated type
问题描述
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
或 let res: Result
有效.
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屋!