代码之家  ›  专栏  ›  技术社区  ›  zardon

Swift-如何比较枚举与相关值?

  •  0
  • zardon  · 技术社区  · 6 年前

    我正在尝试编写一个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
    }
    

    我想做的是:

    orders units 我应该可以测试 matchType perfect , lower higher

    然而,在我的测试中,我必须写下如下内容:

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

    其中(0,0)输入索引,返回值。

    有没有可能在不知道具体数字的情况下对枚举进行比较?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Oletha    6 年前

    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
    }