将通用枚举与关联类型进行比较

时间:2016-04-08 13:46:02

标签: swift enums equality

我有一个结果枚举和错误,如下所示:

enum Result<T>: Equatable {
  case Success(T)
  case Error(ErrorType)
}

func ==<T>(lhs: Result<T>, rhs: Result<T>) -> Bool {
  var equal: Bool = false
  switch (lhs, rhs) {
  case (.Success, .Success):
    equal = true
  case (.Error, .Error):
    equal = true
  default:
    break
  }
  return equal
}

RequestError类似于:

enum RequestError: String,
                   ErrorType,
                   Equatable {
  case NoInternet = "NO_INTERNET_ERROR"
  case Unknown = "UNKNOWN_ERROR"
  case ServerError = "SERVER_ERROR"
}

init?(_ error: NSError?) {
  //do init
}

func ==(lhs: RequestError, rhs: RequestError) -> Bool {
  return lhs.rawValue == rhs.rawValue
}

我正在为Quick + Nimble编写一个规范:

class ResultSpec: QuickSpec {
  override func spec() {

    describe("Result") {

      context("when comparing 2 success results") {

        it("returns true") {
          let equal = Result.Success(5) == Result.Success(5)
          expect(equal).to(beTrue())
        }

      }

      context("when comparing 2 error results") {

        it("returns true") {
          let error = NSError(domain: "", code: 0, userInfo: nil)
          let requestError = RequestError(error)!
          let equal = Result.Error(requestError) == Result.Error(requestError)
          expect(equal).to(beTrue())
        }

      }

    }

  }
}

检查成功通过的第一个测试。第二个没有编译错误:

二元运算符&#39; ==&#39;不能应用于两个&#39;结果&lt; _&gt;&#39;操作数

在这一行:

let equal = Result.Error(requestError) == Result.Error(requestError)

1 个答案:

答案 0 :(得分:2)

我相信编译器告诉你,它不知道应该使用哪种类型的通用Result enum ==操作。您可以将此行替换为任何直接类型规范,因为类型在此处不起作用。像这样:

let equal = Result<String>.Error(requestError) == Result<String>.Error(requestError)