如何解决错误:二进制运算符'=='不能应用于类型'NSExpression.ExpressionType'和'_'的操作数

时间:2019-05-22 12:40:33

标签: ios swift constants nsexpression swift-keypath

当我遇到一个表示

的表达式时,我正在浏览HomeKit Catalog: Creating Homes, Pairing and Controlling Accessories, and Setting Up Triggers中的旧代码
.KeyPathExpressionType

我不知道

.

.KeyPathExpressionType

指的是

的左侧
.

搜索Google并堆积溢出“ KeyPathExpressionType”时,我什么也找不到。与

相同
.ConstantValueExpressionType

我什么都没找到。

每个等式比较

comparison.leftExpression.expressionType == .KeyPathExpressionType

comparison.rightExpression.expressionType == .ConstantValueExpressionType

在下面的代码中,生成一条错误消息,指出:

  

二进制运算符'=='不能应用于类型'NSExpression.ExpressionType'和'_'的操作数

extension NSPredicate {

    /**
        Parses the predicate and attempts to generate a characteristic-value `HomeKitConditionType`.

        - returns:  An optional characteristic-value tuple.
    */
    private func characteristic() -> HomeKitConditionType? {
        guard let predicate = self as? NSCompoundPredicate else { return nil }
        guard let subpredicates = predicate.subpredicates as? [NSPredicate] else { return nil }
        guard subpredicates.count == 2 else { return nil }

        var characteristicPredicate: NSComparisonPredicate? = nil
        var valuePredicate: NSComparisonPredicate? = nil

        for subpredicate in subpredicates {
            if let comparison = subpredicate as? NSComparisonPredicate, comparison.leftExpression.expressionType == .KeyPathExpressionType && comparison.rightExpression.expressionType == .ConstantValueExpressionType {
                switch comparison.leftExpression.keyPath {
                    case HMCharacteristicKeyPath:
                        characteristicPredicate = comparison

                    case HMCharacteristicValueKeyPath:
                        valuePredicate = comparison

                    default:
                        break
                }
            }
        }

        if let characteristic = characteristicPredicate?.rightExpression.constantValue as? HMCharacteristic,
            characteristicValue = valuePredicate?.rightExpression.constantValue as? NSCopying {
                return .Characteristic(characteristic, characteristicValue)
        }
        return nil
    }

更换后,错误消失了

comparison.leftExpression.expressionType == .KeyPathExpressionType

使用

comparison.leftExpression.expressionType.rawValue == NSExpression.ExpressionType.keyPath.rawValue

comparison.rightExpression.expressionType == .ConstantValueExpressionType

使用

comparison.rightExpression.expressionType.rawValue == NSExpression.ExpressionType.constantValue.rawValue

这是正确的吗?有人可以告诉我这个问题的启发吗?

1 个答案:

答案 0 :(得分:1)

该代码已经过时的Swift 2代码。

.KeyPathExpressionType替换为.keyPath,将.ConstantValueExpressionType替换为.constantValue

类型为NSExpression.ExpressionType,请阅读documentation