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

作为函数调用参数的枚举模式匹配

  •  0
  • bogen  · 技术社区  · 7 年前

    enum CarType : Equatable {
        case wheeled(wheels: Int)
        case flying
    
        public static func ==(lhs: CarType, rhs: CarType) -> Bool {
            return lhs.enumName == rhs.enumName
        }
    
        var enumName: String {
            let stuff = "\(self)".split(separator: "(").first!
            return String(describing: stuff)
        }
    
    }
    
    
    var typesPresentAtMyParty = [CarType.wheeled(wheels:4), .wheeled(wheels:4), .flying]
    
    let aKnownType = CarType.flying
    
    if case aKnownType = typesPresentAtMyParty[2] {
        print("Was the type")
    }
    
    func isPresent(type: CarType, inArray: [CarType]) -> Bool {
    
        return inArray.filter {
            if case type = $0 {
                return true
            }
            return false
        }.first != nil
    
    }
    
    func isWheeled(inArray: [CarType]) -> Bool {
    
        return inArray.filter {
            if case .wheeled = $0 {
                return true
            }
            return false
            }.first != nil
    
    }
    
    
    isPresent(type: .flying, inArray: typesPresentAtMyParty)
    isPresent(type: .wheeled, inArray: typesPresentAtMyParty) 
    

    这里的最后一行没有编译。当我能做的时候 if case .wheeled = $0 忽略关联类型作为检查,我找不到在函数调用中执行相同操作的方法 isPresent(type: CarType, inArray: [CarType]) ,发送时 isPresent(type: .wheeled, inArray: typesPresentAtMyParty)

    有没有一种方法可以编写一个只将枚举中有效的模式匹配部分作为参数的函数?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Cristik    7 年前

    不能将部分构造的枚举传递给函数。部分构造的枚举不是有效值,它们只在模式匹配中起作用,因为编译器有一个具体的值要处理—即模式右侧的值。

    isPresent ,您只需使用包含:

    typesPresentAtMyParty.contains { $0 == .flying }
    typesPresentAtMyParty.contains { if case . wheeled = $0 { return true } else { return false } } 
    

    同样地, isWheeled

    func isWheeled(_ carType: CarType) -> Bool {
        if case . wheeled = carType { return true } else { return false }
    }
    

    可以传递给谁 contains :

    let hasWeeled = typesPresentAtMyParty.contains(where: isWheeled)