Swift-如何比较枚举和关联值?

时间:2018-09-06 09:10:45

标签: swift enums xctest

我正在尝试编写XCTest来验证与枚举中关联值的比较。

示例:

enum MatchType : Equatable {
    case perfectMatch(Int, Int)
    case lowerMatch(Int, Int)
    case higherMatch(Int, Int)
}

extension MatchType {
    static func == (lhs: MatchType, rhs: MatchType) -> Bool {
        switch (lhs, rhs) {
        case (.perfectMatch, .perfectMatch):
            return true
        case (.lowerMatch, .lowerMatch):
            return true
        case (.higherMatch, .higherMatch):
            return true
        default:
            return false
        }
    }
}

我如何进行比较以确保正确的枚举而不具体了解Int是什么?

在测试中,我会执行以下操作:

func testPerfectMatch() {
        let orders = [6]
        let units = 6

        let handler = SalesRuleHandler(orders: orders, units: units)

        XCTAssertEqual(handler.matchType!, MatchType.perfectMatch(0, 0))
    }

SalesRuleHandler决定是返回枚举的完全匹配,更低匹配还是更高匹配,

class SalesRuleHandler {

private var orders: [Int]
private var units: Int
var matchType: MatchType?

init(orders: [Int], units: Int) {
    self.orders = orders
    self.units = units
    self.matchType = self.handler()
}

private func handler() -> MatchType? {
    let rule = SalesRules(orders)

    if let match = rule.perfectMatch(units) {
        print("Found perfect match for: \(units) in orders \(rule.orders) at index: \(match.0) which is the value \(match.1)")
        return MatchType.perfectMatch(match.0, match.1)
    }
    else {
        if let match = rule.lowerMatch(units) {
            print("Found lower match for: \(units) in orders \(rule.orders) at index: \(match.0) which is the value \(match.1)")
            return MatchType.lowerMatch(match.0, match.1)
        }
        else {
            if let match = rule.higherMatch(units) {
                return MatchType.higherMatch(match.0, match.1)
            }
        }
    }
    return nil
}

}

我想做的是:

如果我在ordersunits中输入课程,则应该能够测试matchTypeperfectlower还是{{1 }}。

但是,在我的测试中,我必须写类似的东西:

higher

然后将(0,0)放在索引中并返回值。

是否可以在不知道具体数字的情况下对枚举进行比较?

1 个答案:

答案 0 :(得分:3)

您可以使用case访问枚举的关联值。

switch (lhs, rhs) {
case (.perfectMatch(let a, let b), .perfectMatch(let c, let d):
    // check equality of associated values
    return a == c && b == d
// other cases...
}

您还可以使用if语句访问类似的关联值:

if case .perfectMatch(let a, let b) = handler.matchType {
    // do something with a and b
}