如何使用关联值测试 Swift 枚举的相等性 [英] How to test equality of Swift enums with associated values

查看:45
本文介绍了如何使用关联值测试 Swift 枚举的相等性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试两个 Swift 枚举值的相等性.例如:

I want to test the equality of two Swift enum values. For example:

enum SimpleToken {
    case Name(String)
    case Number(Int)
}
let t1 = SimpleToken.Number(123)
let t2 = SimpleToken.Number(123)
XCTAssert(t1 == t2)

但是,编译器不会编译等式表达式:

However, the compiler won't compile the equality expression:

error: could not find an overload for '==' that accepts the supplied arguments
    XCTAssert(t1 == t2)
    ^~~~~~~~~~~~~~~~~~~

我是否必须定义自己的等号运算符重载?我希望 Swift 编译器能够自动处理它,就像 Scala 和 Ocaml 那样.

Do I have do define my own overload of the equality operator? I was hoping the Swift compiler would handle it automatically, much like Scala and Ocaml do.

推荐答案

Swift 4.1+

正如 @jedwidz 所指出的那样,从 Swift 4.1 开始(由于 SE-0185,Swift 也支持合成Equatablecode> 和 Hashable 用于具有关联值的枚举.

Swift 4.1+

As @jedwidz has helpfully pointed out, from Swift 4.1 (due to SE-0185, Swift also supports synthesizing Equatable and Hashable for enums with associated values.

因此,如果您使用的是 Swift 4.1 或更高版本,以下内容将自动合成必要的方法,以便 XCTAssert(t1 == t2) 工作.关键是将 Equatable 协议添加到您的枚举中.

So if you're on Swift 4.1 or newer, the following will automatically synthesize the necessary methods such that XCTAssert(t1 == t2) works. The key is to add the Equatable protocol to your enum.

enum SimpleToken: Equatable {
    case Name(String)
    case Number(Int)
}
let t1 = SimpleToken.Number(123)
let t2 = SimpleToken.Number(123)

Swift 4.1 之前

正如其他人所指出的,Swift 不会自动合成必要的相等运算符.不过,让我提出一个更清洁(恕我直言)的实现:

Before Swift 4.1

As others have noted, Swift doesn't synthesize the necessary equality operators automatically. Let me propose a cleaner (IMHO) implementation, though:

enum SimpleToken: Equatable {
    case Name(String)
    case Number(Int)
}

public func ==(lhs: SimpleToken, rhs: SimpleToken) -> Bool {
    switch (lhs, rhs) {
    case let (.Name(a),   .Name(b)),
         let (.Number(a), .Number(b)):
      return a == b
    default:
      return false
    }
}

这远非理想 - 有很多重复 - 但至少你不需要在内部使用 if 语句进行嵌套切换.

It's far from ideal — there's a lot of repetition — but at least you don't need to do nested switches with if-statements inside.

这篇关于如何使用关联值测试 Swift 枚举的相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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