实施Equatable Void(None)类型 [英] Implement an Equatable Void (None) type

查看:104
本文介绍了实施Equatable Void(None)类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用结果实现结果对象,它定义了一个装箱的结果,例如带有的Optional>枚举:

I am implementing result objects using Result, it defines a boxed result like an Optional with an enum:

public enum Result<T, Error>: Printable, DebugPrintable {
   case Success(Box<T>)
   case Failure(Box<Error>)
   ...
}

Result 定义的 Equatable 协议如下:

public func == <T: Equatable, Error: Equatable> (left: Result<T, Error>, right: Result<T, Error>) -> Bool

因此, T 必须符合 Equatable .

我希望能够有一个 Success (成功),其中包含一个 Void 相似的类型.但是, Void 不是 Equatable ,因为它被定义为空元组:

I would like to be able to have a Success that boxes a Void alike type. But, Void is not Equatable as it's defined as an empty tuple:

typealias Void = ()

目的是能够具有 Result 类型,其中我不关心成功时的a值.

The purpose is to be able to have Result types where I do not care about the a value when succeeds.

是否可能有一个 Equatable Void (或没有值)?

Is it possible to have an Equatable Void (or no value)?

快速思考一下,可以创建一个空的 struct ,但是我正在寻找(如果可能的话)一个更优雅的解决方案.

As quick thoughts, there's the possibility to create an empty struct, but I am looking (if possible) for a more elegant solution.

推荐答案

在Swift 2.0中再次尝试,似乎Void可以初始化为 Void():

Trying again in Swift 2.0, it seems that Void can be initialized as Void():

public enum Result<T, Error: ErrorType> {
    case Success(T)
    case Failure(Error)

    var value: T? {
        switch self {
        case .Success(let v):
            return v
        case .Failure(_):
            return nil
        }
    }

    /// Constructs a success wrapping a `value`.
    public init(value: T) {
        self = .Success(value)
    }

    /// Constructs a failure wrapping an `error`.
    public init(error: Error) {
        self = .Failure(error)
    }
}

enum MyError: ErrorType {
    case AnError
}

let result = Result<Void, MyError>(value: Void())

let success = result.value != nil  // returns true
let error = result.value == nil    // returns false

这篇关于实施Equatable Void(None)类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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