如何快速覆盖泛型谓词的运算符和(&&)?

时间:2019-03-29 01:44:42

标签: swift

我有一个类,其中包含有关在此数据之前进行数据过滤的信息。我想保存过滤谓词,以在将来提供数据时使用它。过滤谓词是其他谓词的组合,我发现根据需要创建用于组合它们的函数将很有用。

func and<T>(_ lth: @escaping (T) -> Bool,
            _ rth: @escaping (T) -> Bool) -> (T) -> Bool {

    return { o in lth(o) && rth(o) }
}

使用示例:

func xIsNot(_ x: Int) -> (Int, Int) -> Bool {
    return { x1, _ in x != x1 }
}

func yIsNot(_ y: Int) -> (Int, Int) -> Bool {
    return { _, y1 in y != y1 }
}

let predicate = someCondition
    ? and(and(xIsNot(7), xIsNot(8)), yIsNot(9))
    : and(xIsNot(2), yIsNot(3))

let points: [(Int, Int)] = ...
let actualPoints = points.filter(predicate)

它工作正常,但可读性不好。以下看起来更好:

let predicate = someCondition
    ? xIsNot(7) && xIsNot(8) && yIsNot(9)
    : xIsNot(2) && yIsNot(3)

是否可以重写运算符&&来替换and?怎么样?

1 个答案:

答案 0 :(得分:2)

您可以尝试以下方法:

infix operator &&& : AdditionPrecedence
func &&&<T>(_ lth: @escaping (T) -> Bool,
        _ rth: @escaping (T) -> Bool) -> (T) -> Bool {
return { x in lth(x) && rth(x) }
}

let predicate = true
? xIsNot(7) &&& xIsNot(8) &&& yIsNot(9)
: xIsNot(2) &&& yIsNot(3)

let points: [(Int, Int)] = [(1,2),(7,3)]
let actualPoints = points.filter(predicate)

以下&&也在起作用。

infix operator && : AdditionPrecedence
func &&<T>(_ lth: @escaping (T) -> Bool,
        _ rth: @escaping (T) -> Bool) -> (T) -> Bool {
return { x in lth(x) && rth(x) }
}

let predicate = true
? xIsNot(7) && xIsNot(8) && yIsNot(9)
: xIsNot(2) && yIsNot(3)